Sending email with html template with images to gmail,exchange - c#

I am using the attached code to send email and images. It is working with gmail.
Now, I want to send to email using html templates. How do I use the attached code to do it?
private void SendEmail1()
{
string strMailContent = "Welcome new user";
string fromAddress = "xxx";
string toAddress = "xxx";
string contentId = "image1";
string path = Server.MapPath(#"Images/ml2.png"); // my logo is placed in images folder
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = "Welcome new User";
LinkedResource logo = new LinkedResource(path,"image/png");
logo.ContentId = "companylogo";
// done HTML formatting in the next line to display my logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
mailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.UseDefaultCredentials = true;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}

Looks like your html isn't formatted correctly
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
Should be
AlternateView av1 = AlternateView.CreateAlternateViewFromString($"<html><body><img src=cid:companylogo/><br>{strMailContent}</body></html>", "text/html");

Looks like your html isn't formatted correctly and you're passing in a null encoding.
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
Should be
AlternateView av1 = AlternateView.CreateAlternateViewFromString($"<html><body><img src=cid:companylogo/><br>{strMailContent}</body></html>", "text/html");

Related

Image not showing in gmail mail body after sending it from asp.net c# net.mail as mail.body

I need to send the qrcode generated from the email to his gmail account. I debugged the code and checked with html visualizer and the qrcode is displaying correctly but cannot see it in gmail message
public void generate_qrcode()
{
try
{
string imgurl;
string code = txtCode.Text;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
imgurl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
//plBarCode.Controls.Add(imgBarCode);
}
SendMail(imgurl);
}
catch (Exception ex)
{
}
}
public void SendMail(String imgurl)
{
string body = "Hello ,<br /><br />Please find your QRcode below<br /><br /><img src=' " + imgurl + " ' height='100' width='100'/><br/><br/>Thanks...";
SmtpClient Smtp_Server = new SmtpClient();
MailMessage e_mail = new MailMessage();
Smtp_Server.UseDefaultCredentials = false;
Smtp_Server.Credentials = new System.Net.NetworkCredential("samplemail527#gmail.com", "Sample527");
Smtp_Server.Port = 587;
Smtp_Server.EnableSsl = true;
Smtp_Server.Host = "smtp.gmail.com";
e_mail = new MailMessage();
e_mail.From = new MailAddress("samplemail527#gmail.com");
e_mail.To.Add(txtCode.Text);
e_mail.Subject = "Email Sending";
e_mail.IsBodyHtml = true;
e_mail.Body = body;
Smtp_Server.Send(e_mail);
}
Base64 images are currently not supported by most email readers. Very unfortunate. You'll need to generate an actual image and attach it to the message with a unique id (like a GUID) and then use that ID as the image tag's src along with the CID prefix.
<img src="cid:GeneratedUniqueId" alt="Your QR Code" />
Here is the good reference to embed image in an email.
Send Email with embedded Images
Maybe you should try to use AlternateView. You have to assign an Id to a resource and use that id within HTML <img> tag. The src attribute should address this Id.Like so:
<img src="cid:ResourceId" />
Don't forget to add linked resource to alternate view.
Here is the full code I used:
Byte[] iconBytes = Convert.FromBase64String(#"iVBOR IMAGE BYTES Hy4vAAN==");
System.IO.MemoryStream iconBitmap = new System.IO.MemoryStream(iconBytes);
LinkedResource iconResource = new LinkedResource(iconBitmap, MediaTypeNames.Image.Jpeg);
iconResource.ContentId = "Icon";
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.To.Add(new MailAddress("recipient#domain.com", "Recipient Name"));
msg.From = new MailAddress("sender#domain.com", "Sender Name");
msg.Subject = "Attach image to mail";
string htmlBody = #"<html><head>";
htmlBody += #"<style>";
htmlBody += #"body{ font-family:'Calibri',sans-serif; }";
htmlBody += #"</style>";
htmlBody += #"</head><body>";
htmlBody += #"<h1>The attached image is here below</h1>";
htmlBody += #"<img src='cid:" + iconResource.ContentId + #"'/>";
htmlBody += #"</body></html>";
AlternateView alternativeView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternativeView.LinkedResources.Add(iconResource);
msg.AlternateViews.Add(alternativeView);
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Port = 25; // You can use Port 25 if 587 is blocked
client.Host = "smtp.yourhost.com";
client.Send(msg);

I want to email the screenshot in tabular format stored in my local using C#?

I want to automate my work by sending the screenshot taken during automation in tabular email format . I had successfully attached as document, but I want it in tabular format. This is code what I had already tried
public static void email_send() {
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:test1.jpeg\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("test1.jpeg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
Attachment att = new Attachment(#"D:/test123.png");
att.ContentDisposition.Inline = true;
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
System.Net.Mail.SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("*****");
mail.To.Add("*******");
mail.Subject = "Test Mail - 1";
mail.Body = String.Format(
"<h3>Client: " + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("******", "******");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
You have missed the attachment.
Your linked resource also needs to be attached to the email. You need to add the following code:
mail.Attachments.Add(att);

How to add a string to a HTML file while sending it as email in asp .net

I am working with asp .net. I want to send an authentication code to user's email when he sign up. I'm using this code to send email. I'm adding a html file to send. How can I add the authentication code to this HTML file?
This is the code which I used to send the html file via Email. So how can I add a string(authenticationCode) to HTML file to send it to the user for authentication.
var fromAddress = new MailAddress("hamza230#gmail.com", "From Hamza");
var toAddress = new MailAddress("usama90#gmail.com", "To Usama");
const string fromPassword = "****";
const string subject = "email";
const string body = "hello world";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.BodyEncoding = Encoding.UTF8;
String plainBody = "Title";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
message.AlternateViews.Add(plainView);
MailDefinition msg = new MailDefinition();
msg.BodyFileName = "~/newsletter.html";
msg.IsBodyHtml = true;
msg.From = "usamaazam10#gmail.com";
msg.Subject = "Subject";
ListDictionary replacements = new ListDictionary();
MailMessage msgHtml = msg.CreateMailMessage("usamaazam10#gmail.com", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
logo.ContentId = "logo";
htmlView.LinkedResources.Add(logo);
LinkedResource cover = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/cover.jpg"), MediaTypeNames.Image.Jpeg);
cover.ContentId = "cover";
htmlView.LinkedResources.Add(cover);
message.AlternateViews.Add(htmlView);
smtp.Send(message);
You can do this for small html pages
string smalHhtml = "<body>"
+ "your some designing"
+ "your Code : " + code
+ "</body>";
Note: This is for small body html and sending verification code via email is usually small html.
You can add the authentication code to the message body, for example:
...
message.Body = body + authenicationCode;
...
Or, if you don't create body as a const then you can create it at the top of your code, for example;
...
const string subject = "email";
string body = "Your authentication code is: " + authenicationCode;
...

Adding a picture header to an HTML email

I'm trying to send an automated email from an application.
The main problem I'm having is that the picture doesn't display.
Secondary to that, the actual resource I'm supposed to be using is a PSD file I can only access with a URL.
The attach code is in from previous experiments, it attaches the file I select from the dialog in line 3
So can anyone tell me where I'm going wrong?
try{
OpenFileDialog diag = new OpenFileDialog();
diag.ShowDialog();
FileInfo inf = new FileInfo(diag.FileName);
string htmlBody = "<html><header><h1>TestPic</h1><br><img src=\"cid:filename\"></header></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource(#inf.FullName, MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
inline.ContentLink = new Uri("PSD_Url.com");
avHtml.LinkedResources.Add(inline);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
Attachment att = new Attachment(inf.FullName);
att.ContentDisposition.Inline = true;
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Test Email";
mail.Body = String.Format(
"<h3>TEST Has Sent You A Mail</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
mail.Attachments.Add(att);
mail.BodyEncoding = Encoding.Unicode;
mail.HeadersEncoding = Encoding.Unicode;
mail.SubjectEncoding = Encoding.Unicode;
SmtpClient smp = new SmtpClient("mailhost.com", 80);
smp.Credentials = new System.Net.NetworkCredential(#"from#gmail.com", #"password");
smp.DeliveryFormat = SmtpDeliveryFormat.International;
smp.Send(mail);
}
catch(SmtpException sEx)
{
throw sEx;
}
.PSD files will not render in most email clients. They are limited to .JPG, .PNG and .GIF. In your case, you might want to run your .PSD through imagemagick or some image converter to convert it first.
Besides that, make sure the image URL is absolute and hosted online and it should work.

Edit HTML Email template at run time in .net code

I below code is to send email by reading the template html, and it works fine. But now my question is how to pass Salutation customerName from my .net code to the template at run time.
StringBuilder strBlr = new StringBuilder();
string strHTML = string.Empty;
string strTempalteHtmlpath = string.Empty;
//create the mail message
MailMessage mail;
string strFrom = ConfigurationSettings.AppSettings["fromAddressForBT"];
string strSubject = "Thanks for choosing Email contact preference";
mail = new MailMessage(strFrom, customerDetails.EmailId);
mail.Subject = strSubject;
//Read Html Template File Path
strTempalteHtmlpath = Convert.ToString(ConfigurationSettings.AppSettings["TemplatePath"]);
strHTML = File.ReadAllText(strTempalteHtmlpath);
strBlr = strBlr.Append(strHTML);
mail.Body = strBlr.ToString();
mail.IsBodyHtml = true;
//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
SmtpClient smtpMail = new SmtpClient(ConfigurationSettings.AppSettings["smtpClient"]);
smtpMail.Send(mail);
mail.Dispose();
Thanks.
This is code for sendemail button
StreamReader sr = new StreamReader(Server.MapPath("Sendpage.htm"));
string body = sr.ReadToEnd();
sr.Close();
body = body.Replace("#NameFamily#", txtNameFamily.Text);
body = body.Replace("#Email#", txtEmail.Text);
body = body.Replace("#Tellphone#", txtTellphone.Text);
body = body.Replace("#Text#", txtText.Text);
body = body.Replace("#Date#", DateTime.Now);
string Time = Convert.ToString(DateTime.Now.ToShortTimeString());
body = body.Replace("#Time#", Time);
SendMail("email that you want to send to it", body);
this is sendmail function code:
private void SendMail(string To, string Body)
{
SmtpClient Mailing = new SmtpClient("mail.domain.com");
MailMessage Message = new MailMessage();
Message.From = new MailAddress("mail#domain.com", "Your name or company name");
Message.Subject = "Subject";
Message.SubjectEncoding = Encoding.UTF8;
Message.IsBodyHtml = true;
Message.BodyEncoding = Encoding.UTF8;
Message.Body = Body;
Message.To.Add(new MailAddress(To));
Mailing.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("mail#domain.com", "password");
Mailing.Credentials = MyCredential; Mailing.Send(Message);
}

Categories

Resources