MailMessage message = new MailMessage(email.From,
email.To,
email.Subject,
email.Body);
message.BodyEncoding = Encoding.GetEncoding("utf-8");
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">";
body += "</HEAD><BODY><DIV>";
body += email.Body.Replace("\r\n", "<br />");
body += "</DIV></BODY></HTML>";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(Regex.Replace(email.Body, #"<(.|\n)*?", string.Empty), null, "text/plain");
message.AlternateViews.Add(plainView);
ContentType mimeType = new ContentType("text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(email.Body, mimeType);
message.AlternateViews.Add(htmlView);
where email.Body and email.Subject is for example "čžćšđščžčžčšđš"
and when i get mail, Subject is ok but body is corrupted like Äžšđ
Problem is in AlternateView.
here:
ContentType mimeType = new ContentType("text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(email.Body, mimeType);
message.AlternateViews.Add(htmlView);
what to do?
According to the following question
How do I set Encoding on AlternateView
the answer is to set the content type of the alternate view appropriately. You are passing null as the encoding, consider passing UTF-8 instead:
AlternateView plainView = AlternateView.CreateAlternateViewFromString(
Regex.Replace(email.Body, #"<(.|\n)*?", string.Empty),
Encoding.UTF8, "text/plain");
You're using null for AlternateView encoding in constructor, replace it with Encoding.GetEncoding("utf-8")
Update:
You've updated your question before it was using null in constructor, anyway there is constructor with encoding parameter.
Related
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.
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.
I am trying to send an email which has embedded images in the body of the message.
The images are encoded as Base64 string. The contents looks as follows:
"<p><span>My Name</span></p><img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA..." width=\"167\" height=\"167\" />"
The base64 string has been cut off for this example.
I am using the following code to send the html as attachment, However, the image in the example is still been refused to be decoded by the emails providers (gmail/outlook). I do not know if i am not doing it properly.
string htmlBody = "<p><span>My Name</span></p><img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA..." width=\"167\" height=\"167\" />";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
var mailTo = Config.Debug ? new MailAddress(Config.DebugEmailAddress) : new MailAddress("myemail#gmail.com");
var mailFrom = new MailAddress("myemail#gmail.com");
var mailMessage = new MailMessage(mailFrom, mailTo) { Subject = "hola q tal", Body = "holaaa", IsBodyHtml = true };
mailMessage.To.Add("myemail#gmail.com");
mailMessage.AlternateViews.Add(avHtml);
var sender1 = new SmtpClient
{
Host = Config.SmtpHost,
Port = 25,
Credentials = new NetworkCredential(Config.SmtpHostUserName, Config.SmtpHostPassword)
};
sender1.Send(mailMessage);
I would appreciate any sugesstions.
I have written below code to embed image in the mail which is being sent from my c# code. But when i check the mail, i get image like an attachment and not as an inline image. (Gmail)
AlternateView htmlBodyView = null;
string htmlBody = "<html><body><h1></h1><br><img src=\"cid:SampleImage\"></body></html>";
AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(bitmap_obj, typeof(Byte[]));
using (MemoryStream logo = new MemoryStream(ba))
{
LinkedResource sampleImage = new LinkedResource(logo, "image/jpeg");
sampleImage.ContentId = "sampleImage";
htmlBodyView.LinkedResources.Add(sampleImage);
p.SendEmail(htmlBodyView);
}
For reference, a full working simplified example:
public void SendMail()
{
LinkedResource logo = new LinkedResource(
"images\\image005.png", //Path of file
"image/png"); //Mime type: Important!
logo.ContentId = "logo"; //ID for reference
//Actual HTML content of the body in an 'AlternateView' object.
AlternateView vw = AlternateView.CreateAlternateViewFromString(
"Hello, this is <b>HTML</b> mail with embedded image: <img src=\"cid:logo\" />",
null,
MediaTypeNames.Text.Html); //Mime type: again important!
vw.LinkedResources.Add(logo);
var msg = new MailMessage() { IsBodyHtml = true };
msg.AlternateViews.Add(vw);
msg.From = new MailAddress("sender#domain.com");
msg.To.Add(new MailAddress("reciever#domain.com"));
msg.Subject = "HTML Mail!";
using (var client = new SmtpClient("localhost", 25))
client.Send(msg);
}
How can I put this ==>
url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB') into new System.Net.Mail.LinkedResource()
to send mail form C#, using background css style with base64 string, not file url.
I wondered this myself and got to this post. I solved it and figured i would share the my solution.
var imageData = Convert.FromBase64String("/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB");
var contentId = Guid.NewGuid().ToString();
var linkedResource = new LinkedResource(new MemoryStream(imageData), "image/jpeg");
linkedResource.ContentId = contentId;
linkedResource.TransferEncoding = TransferEncoding.Base64;
var body = string.Format("<img src=\"cid:{0}\" />", contentId);
var htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
htmlView.LinkedResources.Add(linkedResource);