Send HTML email via C# with SmtpClient - c#

How do I send an HTML email? I use the code in this answer to send emails with SmtpClient, but they're always plain text, so the link in the example message below is not formatted as such.
<p>Welcome to SiteName. To activate your account, visit this URL:
http://SiteName.com/a?key=1234.
</p>
How do I enable HTML in the e-mail messages I send?

This is what I do:
MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
Note that I set the mail message html to true: mail.IsBodyHtml = true;

I believe it was something like:
mailObject.IsBodyHtml = true;

IsBodyHtml = true is undoubtedly the most important part.
But if you want to provide an email with both a text/plain part and a text/html part composed as alternates, it is also possible using the AlternateView class:
MailMessage msg = new MailMessage();
AlternateView plainView = AlternateView
.CreateAlternateViewFromString("Some plaintext", Encoding.UTF8, "text/plain");
// We have something to show in real old mail clients.
msg.AlternateViews.Add(plainView);
string htmlText = "The <b>fancy</b> part.";
AlternateView htmlView =
AlternateView.CreateAlternateViewFromString(htmlText, Encoding.UTF8, "text/html");
msg.AlternateViews.Add(htmlView); // And a html attachment to make sure.
msg.Body = htmlText; // But the basis is the html body
msg.IsBodyHtml = true; // But the basis is the html body

Apply the correct encoding of the Mailbody.
mail.IsBodyHtml = true;

i have an idea , you can add a check box to your project for sending email as html as an option for user , and add this code to enable it :
MailMessage mail = new MailMessage(from, to, subject, message);
if(checkBox1.CheckState == CheckState.Checked )
{
mail.IsBodyHtml = true;
}
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);

If you are using Mailkit,We can use TextBody,HtmlBody and Both for message body. Just write this code. It will help you
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender#address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender#address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = "Hello There";
mailMessage.Body = builder.ToMessageBody();
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user#name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Related

email body coming in a single line

I am sending emails thorugh c#. The body of the mail is dynamic i.e. user fills it in before sending the mail. Issue is the body text is coming in a single line instead of multiple lines as they should.
using (MailMessage mm = new MailMessage(txtEmail.Text.Trim(), email.Trim()))
{
try
{
mm.CC.Add(txtcc.Text.Trim());
mm.Subject = txtSubject.Text.Trim();
mm.Body = txtBody.Text;
MemoryStream pdf = new MemoryStream(bytes);
mm.Attachments.Add(new Attachment(pdf, "Report.pdf"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = txtEmail.Text.Trim();
credentials.Password = txtPassword.Text.Trim();
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
catch (Exception ex)
{
Alert.show1("Could not send the e-mail - error: " + ex.Message, this);
return;
}
}
If you dont need the potential of HTML formatting, you could avoid the problem changing the email format to plain text. This could also avoid user entering text that could be parsed as html.
mm.IsBodyHtml = false;
Otherwise you should change the end line character to html breaking line:
mm.IsBodyHtml = true;
mm.Body = mm.Body.Replace(#"\n", "<br />");
In case of the html format option, It would be wise to follow Fildor's comment and add an alternateView in plain text for email clients that are not html capable.

Send email as HTML is not working. Why?

I have this code:
string email = "myemail#gmail.com";
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(email, "mypassword");
MailMessage mailMessage = new MailMessage(email, toEmail);
mailMessage.Subject = title;
mailMessage.Body = message;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
client.Send(email, toEmail, title, message);
My message is:
message = "hello <b>world</b>."
When I recieve the email, it display the <b>...</b> not making it bold!
What's wrong with it?!
You create a mailMessage variable holding your HTML-formatted message, but then you ignored it and sent the body as plain text.
You need to send the mailMessage itself.
Your message is not a valid html.
Enclose your message with html and body tags
message = "<html><body>hello <b>world</b>.</body></html>"
Also thanks to #SLaks to point that out
In your sample, you should send mailMessage and not message:
client.Send(mailMessage);

SmtpClient sending raw Html

Could anyone tell me why the following code is sending out emails in raw Html? As in, the email looks like when you view a page source.
I have cut down the code so as not to include attachments and from addresses.
If I disable the line with the alternate view the email renders correctly but I also want to send out a plain text version.
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.IsBodyHtml = true;
message.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
message.To.Add(toList);
message.Subject = subject;
message.Body = htmlTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(textTemplate, new ContentType("text/plain")));
client.Send(message);
}
}
Edit: The message was originally sending text as the main body and html as the alternative view but I have run into a problem with accented and foreign characters as described here and wanted to set IsBodyHtml to true, which forces me to set html to the main view.
I had problems with this also but here's a very much cutdown version of code that worked for me...
private MailMessage CreateEmailMessage(string emailAddress) {
MailMessage msg = new MailMessage();
msg.From = new MailAddress(FromEmailAddress, FromName);
msg.To.Add(new MailAddress(emailAddress));
msg.Subject = "Msg Subject here";
string textBody = File.ReadAllText(TextTemplateFile);
string htmlBody = "";
if (EmailFormat == "html") {
htmlBody = File.ReadAllText(HtmlTemplateFile);
foreach (Attachment inline in InlineAttachments) {
inline.ContentDisposition.Inline = true;
msg.Attachments.Add(inline);
}
AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(htmlBody,
new ContentType("text/html"));
msg.AlternateViews.Add(alternateHtml);
AlternateView alternateText = AlternateView.CreateAlternateViewFromString(textBody,
new ContentType("text/plain"));
msg.AlternateViews.Add(alternateText);
}
else {
msg.Body = textBody;
}
return msg;
}
In the end I realised that the 'htmlTemplate' string being passed into the method was defining charset=ISO-8859-1 in the head of the email and therefore overriding any changes I was making in the code.
I changed the charset to UTF-8, and restored my code to this:
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.To.Add(toList);
message.Subject = subject;
message.Body = textTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType("text/html")));
client.Send(message);
}
}
and can now send both text and html templates as well as cover the accented characters problem.

ASP.NET app to send an mail with a hyperlink

MailMessage message = new MailMessage();
message.From = new MailAddress("hkar#gmail.com");
message.Subject = "Subject";
message.Body = "Please login";
SmtpClient smtp = new SmtpClient();
message.To.Add("karaman#gmail.com");
smtp.Send(message);
I want to have a hyperlink in the body of sent mail where it says "login". How can I do that?
message.Body = "Please login";
Make sure you highlight when sending that the content is HTML though.
message.IsBodyHTML = true;
Set the message to message.IsBodyHTML = true
Login
message.Body = string.Format("Click <a href='{0}'>here</a> to login", loginUrl);
Format the message as HTML and make sure to set the IsBodyHtml property on the MailMessage to true:
message.IsBodyHtml = true;
System.Text.StringBuildersb = new System.Text.StringBuilder();
System.Web.Mail.MailMessage mail = new System.Mail.Web.MailMessage();
mail.To = "recipient#address";
mail.From = "sender";
mail.Subject = "Test";
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
sb.Append("<html><head><title>Test</title><body>"); //HTML content which you want to send
mail.Body = sb.ToString();
System.Web.Mail.SmtpMail.SmtpServer = "localhost"; //Your Smtp Server
System.Web.Mail.SmtpMail.Send(mail);
You just have to set the format of body to html then you can add html element within the bosy of mail message

Is there anyway to display Right To Left plain text mails?

I'm sending mails in c# using SmtpClient.
i'm sending the mails as plain text:
message.IsBodyHtml =False;
how can I send them as RTL? with HTML mails it's very easy-just tag them as RTL.
Sample code:
public void SendEmail(bool isJapanese)
{
try
{
MailAddress from = new MailAddress(FromEmail,FromDisplay);
MailAddress to = new MailAddress(ToEmail, ToDisplay);
MailMessage message = new MailMessage( from, to);
message.Subject = Subject;
if (!IsHTML)
Body = Body.Replace("<br/>", "\r\n").Replace("<br/>", "\r").Replace("<br/>", "\n");
message.Body =Body;
message.BodyEncoding = Encoding.UTF8;
message.SubjectEncoding = Encoding.UTF8;
message.IsBodyHtml = IsHTML;
smtpClient.Send(message);
}
catch (Exception ex)
{
ex.HelpLink += "class MailSender, fn SendMail(); ";
Log(ex);
}
}
there is no way to indeciate alignment of plain text mails.
by the way- Gmail is autodetcting RTL languages but this is the only provider i see that doe's that.

Categories