C#. How to avoid image attached while sending mail - email

I am trying to send email from my.net application.
I have included an image in it. I get the image in the email. Issue is the image is coming also as an attachment.
I need only the inline image. Not attachment. Any option to remove the attachment?
I have include the code below
body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
body += "</FONT></DIV><DIV><img width=600 height=100 id=\"_x0000_i1028\" src=\"cid:cid1\" alt=\"KPMG LINK\"></DIV></BODY></HTML>";
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, null, "text/plain");
AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
LinkedResource resource = null;
resource = new LinkedResource(ImagePath, new ContentType("image/png"));
resource.ContentId = "cid";
alternate.LinkedResources.Add(resource);
message.AlternateViews.Add(alternate);
message.AlternateViews.Add(alternateHtml);
smtp.Send(message);

Try from any one of below two options: (Reference)
Option 1:-
System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(#"imagepath\filename.png");
inline.ContentDisposition.Inline = true;
Option 2 :-
using (var client = new SmtpClient())
{
MailMessage newMail = new MailMessage();
newMail.To.Add(new MailAddress("you#your.address"));
newMail.Subject = "Test Subject";
newMail.IsBodyHtml = true;
var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"));
inlineLogo.ContentId = Guid.NewGuid().ToString();
string body = string.Format(#"
<p>Lorum Ipsum Blah Blah</p>
<img src=""cid:{0}"" />
<p>Lorum Ipsum Blah Blah</p>
", inlineLogo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(inlineLogo);
newMail.AlternateViews.Add(view);
client.Send(newMail);
}

Related

Convert "," to ";" in a CSV file Google script

With the below code my goal is to extract a sheet from the Google sheet file in CSV format. However, when I want to convert the , to ; the following error message appears:
r.join is not a function
Could you please help me to solve this problem.
Also, do you think it is possible to download this new file directly to the desktop of the computer ?
function sheetToCsv(){
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Int_Module";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var newfile = [result].map(r => r.join(";")).join("\n");
newfile.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
}
I understand that there is 2 questions ... how to produce CSV file with semi-colon, and how to download the file directly to your PC.
1- To produce the csv content, try
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
2- To download, you will have to go through an html page.
Try this for both needs
function downloadMyCSVFile() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
var html = HtmlService.createHtmlOutput(`
<html><body onload="document.getElementById('dwn-btn').click()">
<textarea id="text-val" rows="10" style="display:none;">${content}</textarea>
<input type="button" id="dwn-btn" value="Download text file" style="display:none;"/>
<script>
window.close = function(){window.setTimeout(function(){google.script.host.close()},100)}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "${sh.getName()}.csv";
download(filename, text);
close();
}, false);
</script>
</body></html>
`)
.setWidth(250).setHeight(100);
SpreadsheetApp.getUi().showModalDialog(html, "Downloading ...");
}

ktor send email with html template

I am wondering what is the correct way of sending HTML templates with ktor via email.
This answer Sending Emails From Ktor Application can help inline HTML, or simple string but not hbs or other templates which can be used in ktor.
email service will work, but I do want to use a template. And doing it via MustacheContent will not work
package com.meet.utils.email
import com.meet.utils.Constants
import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.HtmlEmail
fun sendForgotPasswordEmail(token: String, emailTo: String) {
val email = HtmlEmail()
email.hostName = "smtp.sendgrid.net"
email.setSmtpPort(587)
email.setAuthenticator(
DefaultAuthenticator(
"apikey",
"API_KEY"
)
)
email.isSSLOnConnect = true
email.setFrom(Constants.EMAIL_FROM)
email.subject = "Forgot Password"
email.setHtmlMsg("<html><body><div style='background:red;'>Hello</div></body></html>")
email.addTo(emailTo)
email.send()
}
What I want to do is
email.sendTemplate(MustacheContent("forgotPassword.hbs", mapOf("token" to token)))
how I can send this?
resources/templates/reset.hbs
<html>
<body>
<h1>Hello</h1>
<p>Please visit the link below to reset your password</p>
Reset your password
</body>
</html>
You can compile and render a template via a Mustache factory to get an HTML string. Here is an example:
val factory = DefaultMustacheFactory("templates")
embeddedServer(Netty, port = 3333) {
install(Mustache) {
mustacheFactory = factory
}
routing {
post("/") {
val content = MustacheContent("forgotPassword.hbs", mapOf("token" to "my-token"))
val writer = StringWriter()
factory.compile(content.template).execute(writer, content.model)
val html = writer.toString()
// Send email with an HTML
}
}
}.start(wait = true)

Change the design of email body

I have written the code for sending email in email.js as follows:
Accounts.emailTemplates.siteName = "xyz";
Accounts.emailTemplates.from = "xyz <admin#xyz.com>";
Accounts.emailTemplates.verifyEmail = {
subject() {
return "[xyz] Verify Your Email Address";
}
};
Accounts.emailTemplates.verifyEmail.text = function( user, url) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace( '', '' ),
supportEmail = "support#xyz.com",
emailBody = `To verify your email address (${emailAddress}) visit the following link:\n\n${urlWithoutHash}\n\n If you did not request this verification, please ignore this email. If you feel something is wrong, please contact our support team: ${supportEmail}.`;
return emailBody;
}
The email is working and all I want is to change the Design. How to design the email body? Can I insert the html code inside the email body so that I can have a proper responsive email design? I have tried in many ways. Can anyone please help me out?
I have used mail gun API for sending emails is there anyway to use template.
I have tried with grunt email template and am struck with that I need help to get complete my task.
You can create an email template using SSR package.
Accounts.emailTemplates.verifyEmail.html = function (user, url) {
SSR.compileTemplate( 'registartionEmail', Assets.getText( 'email_templates/registration_confirm.html' ) );
var emailData = {
x: y;
};
return SSR.render( 'registartionEmail', emailData );
};
To handle the process of converting templates into raw HTML on the server, you need to add a package to your application called meteorhacks:ssr. Once you have the package installed, you can store plain HTML files inside your /private directory and then convert them later, passing any data to replace handlebars helpers like {{name}} in the process.
For example, here is some code I have used to send a welcome email when new users register:
import { SSR } from 'meteor/meteorhacks:ssr';
const getHTMLForEmail = (templateName, data) => {
SSR.compileTemplate(templateName, Assets.getText(`email/templates/${templateName}.html`));
return SSR.render(templateName, data);
};
const sendEmail = (emailAddress, html) => {
if (emailAddress.includes('#')) {
const emailData = {
to: emailAddress,
from: 'Test Email <hello#test.io>',
subject: 'Welcome aboard, team matey!',
html,
};
Meteor.defer(() => Email.send(emailData));
}
};
export const sendWelcomeEmail = (user, profile) => {
let email;
if (user.services.facebook) {
email = user.services.facebook.email;
} else if (user.services.google) {
email = user.services.google.email;
}
const data = {
email,
name: profile && profile.name ? profile.name : '',
url: 'www.google.com',
};
const html = getHTMLForEmail( 'welcome-email', data );
sendEmail(data.email, html);
};
You will find the following two articles from Meteor Chef very useful (also shows how the html email template looks like):
Using the email package
Sign up with email verification

Getting 500 error while creating vertex using Rest API

I am writing a SSIS script component for importing data into orientdb using RestAPI but i am getting error 500. Please i am stuck here. Is there anyone who can help me with this. I am using version 2.1.7 community edition.
Here is my code so far.
Uri address = new Uri("http://localhost:2480//command/SQ-DB/sql/");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json; charset=UTF-8";
request.ContentType = "application/json";
string username = "root";
string password = "***";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
StringBuilder data = new StringBuilder();
// string link = "{\"statements\" : [ {\"statement\" : \"CREATE ( company: Accounts { Name:" + Row.companyname + "} ) RETURN company\"} ]}";
string link= "CREATE VERTEX Contacts CONTENT { 'name' : "+ Row.fullname+", 'Email' : "+ Row.emailaddress1+", 'Phone' : "+ Row.telephone1 + ", 'ContactId' : "+ Row.contactid+", 'City' : "+Row.address1city+"}" ;
data.Append(HttpUtility.UrlEncode(link));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
request.Headers.Add("Accept-Encoding", "gzip,deflate");
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
It will be a great help if anyone can point the issue. Thank you

Post to Facebook Page from Facebook App

I want to post from my Facebook app to one of my pages using app_id and app_secret. It will help me to post directly without log in to Facebook.
I'm able to post on my profile, but not on my page!
Here is my code:
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type={2}",
app_id, app_secret, "client_credentials");
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/my-page-FB-ID/feed", new { desctiption = description, picture = picture, link = link, caption = caption, type = type });