How to format Asp.net SMTP Email with HTML? - c#

I was doing an SMTP email that will send the order details to the customer email after the purchase. I had successfully sent it to the customer but the format is a little weird.
Below is the output it sends to the customer email.
Your order is successful!
------------------------------------------------
Order ID : Order20465230820207quiw< br />Order Date : 8/30/2020< br />Send To : 81,JALAN KENARI MERAH 8
<br /> Kedah< br /> 05200< br />Grand Total : 499< br />< br />< br />Thank You for purchasing with us!
But it expects it to format like this :
Your order is successful!
------------------------------------------------
Order ID : Order20465230820207quiw
Order Date : 8/30/2020
Send To : 81,JALAN KENARI MERAH 8
Grand Total : 499
Thank You for purchasing with us!
Here is the code:
lblmail.Text = "Your order is succesful! <br />" +
"------------------------------------------------ <br />" +
"Order ID : " + Session["OrderID"].ToString() + "< br />" +
"Order Date : " + Session["orderDate"].ToString() + "< br />" +
"Send To : " + Session["address"].ToString() + "< br />" +
" " + Session["state"].ToString() + "< br />" +
" " + Session["zipcode"].ToString() + "< br />" +
"Grand Total : " + Session["GrandTotal"].ToString() + "< br />" +
"< br />< br />Thank You for purchasing with us!" ;
Do note that I had enabled the HTML is the email body with this code:
MailMessage mm = new MailMessage();
mm.IsBodyHtml = true;
What is the problem here? The code seems to be fine but the output is not what I expected.

You need to add HTML insted of normal text
Code
var htmlContent ="<!DOCTYPE html>
<html>
<body>
<h3><p>Your order is successful!</p></h3>
<p>----------------------------------</p>
<p>Order ID : Order20465230820207quiw</p>
<p>Order Date : 8/30/2020</p>
<p>Send To : 81,JALAN KENARI MERAH 8</p>
<p>Grand Total : 499</p>
<p>Thank You for purchasing with us!</p>
</body>
</html>";
using (MailMessage mm = new MailMessage())
{
mm.Body = htmlContent;
mm.IsBodyHtml = true;
}
It's working fine with your mail functionality

make sure that your HTML tags are written correctly "< br />" remove the spaces, with is this way you make sure that the server dose not send it as text.
< br /> To this <br/>

Related

Using apostrophe in email subject while sent email via gmail api creating an issue

While sent email using below subject which apostrophe replacing with another characters
Actual Subject : We’ll make 100,800 cold calls for you
Mail Shows Subject : We’ll make 100,800 cold calls for you
Issue happens when I'm sent email via api , when sent email from SMTP it's working fine
Please check my api code below
string msg = "From: " + FromName + "<" + From + ">" + " \r\n" +
"To: " + ToName + "<" + To + ">" + " \r\n" +
"BCC: " + BCCEmail + " \r\n" +
"Subject: " + Subject + " \r\n" +
"Message-ID: mID_" + messageID + "\r\n" +
"References: "+encryptMessageID + "\r\n" +
"In-Reply-To: " + encryptMessageID + "\r\n" +
"Content-Type: " + contentType + "; charset=us-ascii\r\n\r\n" + Body;
dynamic objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg) };
if (!string.IsNullOrEmpty(messageThreadID))
objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg), threadId = messageThreadID };
var _objSendMsg = JsonConvert.SerializeObject(objSendMsg);
var strSendMsg = new StringContent(_objSendMsg, UnicodeEncoding.UTF8, "application/json");
When same content i'm applying in body with apostrophe working fine for body
Please check attached screenshot
Email copy
You need to base64_encode of the subject header your sending it as plain text. the API is getting confused.
Subject: " + Convert.ToBase64String(Subject) + " \r\n" +

Couldn't find image with CID in windows service

I am testing the sending of an email with images using CID tag, I make a desktop application that only runs the mail, the program asked me to also place them in the debug folder of the project apart from the folder where I put them, Now I send it to a windows service but it tells me that
Could not find file 'C:\WINDOWS\system32\ img.png
I already put the image in that folder but it still gives me the same error, the image is type .png, this is my email code
private void SendMAil()
{
string htmlBody = "<!DOCTYPE html>" +
"<html xmlns = 'http://www.w3.org/1999/xhtml'>" +
"<head>" +
"<meta http - equiv = 'Content-Type' content = 'text/html; charset=UTF-8'/>" +
"<title> Demystifying Email Design</title>" +
"<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0'/>" +
"</head>" +
"<body style = 'margin: 0; padding: 0;'>" +
"<table align = 'center' border = '0' cellpadding = '0' cellspacing = '0' width = '900' > " +
"<tr>" +
"<td align='left' bgcolor='#F8F8F8' style='padding: 15px 0 15px 0;border-bottom-width:6px;border-bottom-color:#225100;border-bottom-style:solid;'>" +
" <img src=\"cid:img\"' width='90' height='40'>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td bgcolor = '#ffffff' style='padding:30px 30px 65px 30px'>" +
"HELLO!!!"+
"</td>" +
"</tr>" +
"<tr>" +
"<td bgcolor = '#FFFFFF' align='center' style='padding: 15px 0 15px 0;border-top-width:1px;border-top-color:#FA5300;border-top-style:solid;'>" +
"</td>" +
"</tr>" +
"</table>" +
"</body>" +
"</html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("img.png", MediaTypeNames.Image.Jpeg);
inline.ContentId = "img";
avHtml.LinkedResources.Add(inline);
Attachment att1 = new Attachment(#"img\img.png");
att1.ContentDisposition.Inline = true;
mail.From = new MailAddress("xx#xx.com");
mail.To.Add("xx#xx.com");
mail.Subject = "Alerta Estado Tags";
mail.Body = inline.ContentId;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient
{
Credentials =
new NetworkCredential("xx#xx.com", "****"),
Host = "smtp.gmail.com",
Port = 000,
EnableSsl = true
};
smtp.Send(mail);
mail.Dispose();
}
Where do I put the images? and What would be the path?
Please review your code, you are using 2 paths for the img.png file, once under without specifying any additional path, which will result in the program trying to search the file under the current working directory (system32 in your case) and once searching inside the img folder (which should also be in your current working directory).
There are other issues in your code example,
you are not associating the avHtml to the email message anywhere.
mail.AlternateViews.Add
where do you initializing the mail object?
But the most important, is how do you execute your program?
I assume you are using the windows command line and dragging the program with its full path, which causes your current working directory to stay under System32 (which is the default directory of CMD when running as Administrator.
Therefore, it looks for img.png and img/img.png under System32
The cid tag is used for resources embedded in the email itself. So you have to add the image as an attachment with a certain code (don't have it at the ready at the moment).
That said: don't use it. It's obsolete and blocked by many email clients. Dump your pictures on a webserver and just link to them.

How to resolve newline character when sending an email using SMTP

string strTheBody = #"First Name: " + tbFirst.Text + "\nLast Name: " + tbLast.Text + "\nAddress 1: " + tbAdd1.Text + "\nAddress 2: " + tbAdd2.Text + "";
strTheBody += #"\nCity: " + tbCity.Text + "\nState: " + ddlTechState.SelectedValue + "\nZip Code: " + tbZip.Text + "\nDOB: " + tbDOB.Text + "\nEmail Address: " + tbEmail.Text + "";
strTheBody += #"\nLast Doctor visited: " + ddlTechProvider.SelectedValue + "\nIssue: " + ddlTechIssues.SelectedValue + "\n\nComments: " + HttpUtility.HtmlEncode(tbComments.Text) + "";
MailMessage mmSendEmail = new MailMessage();
mmSendEmail.To.Add("myemail#myweb.com");
mmSendEmail.From = new MailAddress(tbEmail.Text);
mmSendEmail.Subject = "Contacting about " + ddlTechIssues.SelectedValue;
mmSendEmail.Body = strTheBody;
SmtpClient scSend = new SmtpClient("mysmtp.myisp.com");
scSend.Send(mmSendEmail);
Sends the email like this:
First Name: first
Last Name: last
Address 1: my address 1
Address 2: \nCity: some city
State: NV
Zip Code: 90320
DOB: 08/08/2013
Email Address: myemail#email.com\nLast Doctor visited: 0
Issue: Result
Comments: This is a comment
How can I resolve the issue with the \n being displayed if the value is empty and when there is an email address.
# symbol means to read that string literally, and don't interpret
control characters
https://stackoverflow.com/a/3312007/3087342
I suggest using StringBuilder instead, will remove these type of errors and makes your code generally a lot more readable - in terms of formatting the email anyway.

Displaying Base64 image

I have images stored as Base64, but I'm having trouble displaying them. I'm using ASP.NET, and here is part of the code:
int visitorId = int.Parse(Request.QueryString["id"]);
classes.Visitor visitor = new classes.Visitor(visitorId, PageExtension_CurrentUser.Community.Id);
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append(#"<tr><td colspan=""2""><div style=""width:320px; height:240px; border: 1px dotted #000;"">");
if (visitor.VisitorImage != "")
{
sb.Append(#"<img style=""width:320px; height:240px;"" alt="" src=""data:image/jpeg;base64, " + visitor.VisitorImage + #""" />");
}
else
{
sb.Append(#"No image");
}
sb.Append("</div></td></tr>");
sb.Append("<tr><td style='width:200px;'><b>Visitor Name</b></td><td>" + visitor.GetFullname() + "</td></tr>");
sb.Append("<tr><td><b>Company/Address</b></td><td>" + visitor.AddressOrCompany + "</td></tr>");
Interesting to note, is that:
the DIV with dotted border displayed, however no image is shown.
The remaining are not printed out??
The image data is fine, I have already tested it on http://base64online.org/decode/ and i see the image im using for testing.
I am assuming it is the data, but why is it not shown? Any ideas?
This line of code is wrong:
sb.Append(#"<img style=""width:320px; height:240px;"" alt="" src=""data:image/jpeg;base64, " + visitor.VisitorImage + #""" />");
It should be:
sb.Append(#"<img style=""width:320px; height:240px;"" alt="""" src=""data:image/jpeg;base64, " + visitor.VisitorImage + #""" />");

email working local but not on server

I'm trying to send out an email after a button click event. When testing from my local machine everything runs smooth, the email get send out and I get the popup message notifying me that the "call has been resolved". But running from server side the page "hangs" - the screen is dimmed out which should happen until the email is sent off, but it stays like that. the email does not get sent out from server side....
This is what I've done:
My code:
MailMessage Mail = new MailMessage();
Mail.Subject = "Call Resolved";
Mail.To.Add(useremail);
// Mail.To.Add(useremail);
Mail.From = new MailAddress("notifications#oep.co.za");
// string path = Server.MapPath(#"..\Images\SOSLetterhead.png");
// string path = PopulateEmailImage();
string path = Server.MapPath(#"\Images\ItsmBCXHeader.gif");
LinkedResource logo = new LinkedResource(path);
logo.ContentId = "header";
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><head>" +
#"<meta content=""text/html; charset=utf-8"" http-equiv=""Content-Type""/> " +
#"<title></title></head><body ><style> " +
#".auto-style1 {width: 188px; }table tr td{ border:solid;border-width:1px;} .link{color:red;}</style> " +
#"<img alt="""" height=""130"" src=""cid:header"" width=""675"" /> " +
#"<div style=""color:red; font-weight:bold; text-align:left; border:none; margin-right:20%;"" > " +
#"<h3>This message is sent on behalf of <br /> The Business Connexion Global Service Management Centre</h3> " +
#"<h5><i>Please do not respond to the sender as this mailbox does not receive return mail. <br /> " +
#"Use the Link located at the bottom of the e-mail to Respond </i></h5> </div><br />" +
#"<div>Dear <b>" + CustName + "</b></div><br /> " +
#"<div>We are pleased to inform you that your reported Incident <b>" + incidentNo + "</b>, has been resolved. </div><br /> " +
#"<div><b>Incident Summary report as follows:</b></div> <br /> " +
#"<table style=""width:45%; border:solid; border-width:3px; background-color:#E2E2E2;""> " +
#"<tr><td class=""auto-style1""><b>Incident Number:</b></td><td>" + incidentNo + "</td> " +
#"<tr><td class=""auto-style1""><b>Status:</b></td><td>" + stats + "</td></tr> " +
#"<tr><td class=""auto-style1""><b>CI Serial No:</b></td><td>" + serialNo + "</td></tr> " +
#"<tr><td class=""auto-style1""><b>Incident Summary:</b></td><td>" + incidentSum + "</td></tr> " +
#"<tr><td class=""auto-style1""><b>Incident Notes:</b></td><td>" + incidentNotes + "</td></tr> " +
#"<tr><td class=""auto-style1""><b>Resolution:</b></td><td>" + resolution + "</td></tr> " +
#"</table><br /><div> " +
#"If you have any queries or if you would like to change your contact details, please contact the <br /> Global Service Management Centre. " +
#"</div><br /><div> " +
#"Click here if you would like to contact the Global Service Management Centre via e-mail </div> " +
#"<br /><div><b>011 266 1102</b> (National, South African number) <br /><b>+27 (0) 266 1102</b> (International number)<br /> " +
#"E-mail queries to spoc#bcx.co.za <br /></div><br /><div><b>Yours in service <br /> " +
#"Global Service Management Centre</b></div></body></html>", null, MediaTypeNames.Text.Html);
av1.LinkedResources.Add(logo);
Mail.AlternateViews.Add(av1);
System.Configuration.Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;
string password = mailSettings.Smtp.Network.Password;
string username = mailSettings.Smtp.Network.UserName;
}
SmtpClient SMTP = new SmtpClient();
SMTP.Send(Mail);
And my web.config:
<mailSettings>
<smtp deliveryMethod="Network" from="Notifications#smart-office.co.za">
<network host="host" userName="notifications#oep.co.za" password="password" port="25" />
</smtp>
</mailSettings>
I have removed the password and host for security reasons... Any help will be greatly appreciated! this works on another site, but not on this one.....
I had once this problem, I changed the value of EnableSsl field of SmtpClient to false before publishing and it worked for me, If you already have false then change it to true
Check in windows Event viewer for more details. it might log information if its problem with environment.

Categories