BodyBuilder bodyBuilder = new BodyBuilder();
messageContent.Body = "<b>This is a test mail</b>";
bodyBuilder.HtmlBody = messageContent.Body;
I tried to embed my body to a bodybuilder but when I received the email, it returned an empty body. I have an exception that would throw an argument if the body is empty..
Using a BodyBuilder like you are doing is probably the easiest way.
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<b>This is some html text</b>";
bodyBuilder.TextBody = "This is some plain text";
message.Body = bodyBuilder.ToMessageBody();
client.Send(message);
MimeKit Documentation - Creating Messages
var message = new MimeMessage();
message.Body = new TextPart ("html") { Text = "<b>Test Message</b>" };
"A TextPart is a leaf-node MIME part with a text media-type. The first argument to the TextPart constructor specifies the media-subtype: plain, html, enriched, rtf, and xml."
One other option here if you want to be strict;
msg.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = "<b>html content</b>" };
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = body;
bodyBuilder.TextBody = "-";
message.Body = bodyBuilder.ToMessageBody();
In some mail ISP, you should always set bodyBuilder.TextBody by value.
Related
I am trying to attach the mail template in Mail Kit I am using .NET Core
here is my code
//From Address
string FromAddress = "info#gorollo.com";
string FromAdressTitle = "Gorollo";
//To Address
string ToAddress = email;
string Subject = subject;
string BodyContent = message;
var body = new BodyBuilder();
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress
(FromAdressTitle,
FromAddress
));
mimeMessage.To.Add(new MailboxAddress
(
ToAddress
));
mimeMessage.Subject = Subject;
using (var client = new SmtpClient())
{
client.Connect("smtp.mailgun.org", 587, false);
client.Authenticate(
"info#gorollo.com",
"password"
);
await client.SendAsync(mimeMessage);
await client.DisconnectAsync(true);
}
i saw many examples but not able to find the exact solution
so please anyone help me to sort out the problem
I have to attach Signup template in my mail here.
You're almost here. You can use the BodyBuilder to add text or HTML to the body. Either use the TextBody or HtmlBody property to set text or HTML respectively. Use the ToMessageBody() method to create a MimeEntity instance which you can use as the mail body.
Example:
var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello, World!</h1>";
message.Body = bodyBuilder.ToMessageBody();
I have a variable name that holds a hyperlink; I would like to send the hyperlink within an email.
I can send the email ok, but the hyperlink appears as text i.e.[http://www.google.com]Click here
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"], "FileTransfer");
mailMessage.Subject = "FileTransfer";
var body = new StringBuilder();
body.AppendFormat("<html><head></head><body> Hello World" + "<br />" + "<a href='{0}'>Click here</a></body></html>", link);
mailMessage.IsBodyHtml = true;
mailMessage.Body = body.ToString();
mailMessage.To.Add(new MailAddress(toEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
Try replacing this...
body.AppendFormat("<html><head></head><body> Hello World" + "<br />" + "<a href='{0}'>Click here</a></body></html>", link);
with this
body.Append("<html><head></head><body> Hello World" + "<br />" + "Click here</body></html>");
According to https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx
It seems like you have to set the content type and create an alternate view. Or if you don't want to have a plaintext version, set the default view to text/html
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
recipients,
"This e-mail message has multiple views.",
"This is some plain text.");
// Construct the alternate body as HTML.
string 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></BODY></HTML>";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
Some email provider software won't be capable of displaying text/html. Whether this is a protective measure or just lack of support, I believe this would be the best solution since it compensates for both cases.
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.
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
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());
}