I'm trying to generate a MailMessage and set various attachments to it. The inline attachments always appear to the recipient as either jpeg, png, or other image files if I add them as an Attachment type. The code I used for this approach:
var mailMessage = new MailMessage();
// Set To, From, Body, Subject, etc.
foreach(var att in self.Attachments) {
byte[] content = att.GetBytes();
var attachment = new Attachment(new MemoryStream(content), att.Name);
if(att.IsInline){
attachment.ContentId = att.Name;
attachment.ContentDisposition.Inline = true;
attachment.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
}
mailMessage.Attachments.Add(attachment)
}
var view = AlternateView.CreateAlternateViewFromString(mailMessage.Body, Encoding.UTF8, MediaTypeNames.Text.Html);
mailMessage.AlternateViews.Add(view);
If I add them as a LinkedResource then they show up as dat files in the attachment section. Code:
var mailMessage = new MailMessage();
// Set To, From, Body, Subject, etc.
var view = AlternateView.CreateAlternateViewFromString(mailMessage.Body, Encoding.UTF8, MediaTypeNames.Text.Html);
foreach(var att in self.Attachments) {
byte[] content = att.GetBytes();
if(att.IsInline) {
var inline = new LinkedResource(new MemoryStream(content), att.ContentType);
inline.ContentId = att.Name;
view.LinkedResources.Add(inline);
}
else {
mailMessage.Attachments.Add(new Attachment(new MemoryStream(content),
att.Name));
}
}
mailMessage.AlternateViews.Add(view);
Both approaches generate the correct email and inject the inline attachments into the body of the email. Neither show the inline attachments in the attachment section while previewing the email in outlook. Both show the inline attachments when receiving the email in outlook. I have made sure that the outlook settings are as follows in the mail section of Outlook Options: "Compose message in this format: HTML" and "When sending messages in Rich Text format to Internet recipients: Convert to HTML format".
Any suggestions would be greatly appreciated as the additional attachments are creating confusion to the end users.
I stumbled on this question having had the same problem, and for me the solution was to add the type of the attachment.
Change this
var inline = new LinkedResource("logo.png");
To this
var inline = new LinkedResource("logo.png", "image/png");
It looks as if you are already doing this, but perhaps that wasn't working as intended?
Thanks to this page for providing the answer:
https://www.codeproject.com/articles/31897/embed-an-image-in-email-using-asp-net
Related
Hi We are trying to develop a mail sending system using MailKit. We have a set of Email Templates which are created using WORD and saved as MHTML files. The whole thing is working fine, when we use MailKit to create a MimeMessage from the MHT file.
But post creating this message, I am not able to see a way of adding attachments to this.
Currently we are trying the following.
private void SendEmail(string templatePath, List<string> attachments)
{
// Load the MHT Template
var mimeMessage = MimeMessage.Load(templatePath);
mimeMessage.From.Add(new MailBoxAddress("test#Test.com"));
mimeMessage.To.Add(new MailBoxAddress("test#Test.com"));
foreach (var attachment in attachments)
{
var fileAttachment = new MimePart()
{
ContentObject = new ContentObject(File.OpenRead(Path.Combine(attachment), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Binary,
FileName = Path.GetFileName(attachment)
};
// Attachments is a read only Enumerable here.
mimeMessage.Attachments.Add
}
}
I add the attachment by the BodyBuilder:
BodyBuilder _body = new BodyBuilder
{
HtmlBody = message
};
_body.Attachments.Add(_fileName, _stream);
_email.Body = _body.ToMessageBody();
See this post stackoverflow
You will need to traverse the MIME tree structure of the message until you find the Multipart that you would like to add the "attachment" to and then use the Multipart.Add() method.
Keep in mind that a message is a nested tree structure and not a well-defined structure which has only 1 message body (or even just 2) and a list of attachments. It's a whole lot more complicated than that, so there's literally no way for MimeMessage.Attachments to "do the right thing".
For the general case, you can probably get away with something like this:
var message = MimeMessage.Load(fileName);
var attachment = new MimePart("application", "octet-stream") {
FileName = attachmentName,
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent(attachmentStream)
};
if (!(message.Body is Multipart multipart &&
multipart.ContentType.Matches("multipart", "mixed"))) {
// The top-level MIME part is not a multipart/mixed.
//
// Attachments are typically added to a multipart/mixed
// container which tends to be the top-level MIME part
// of the message (unless it is signed or encrypted).
//
// If the message is signed or encrypted, though, we do
// do not want to mess with the structure, so the correct
// thing to do there is to encapsulate the top-level part
// in a multipart/mixed just like we are going to do anyway.
multipart = new Multipart("mixed");
// Replace the message body with the multipart/mixed and
// add the old message body to it.
multipart.Add(message.Body);
message.Body = multipart;
}
// Add the attachment.
multipart.Add(attachment);
// Save the message back out to disk.
message.WriteTo(newFileName);
As the title, is MailKit supported to send file?
If yes, how can I do it?
Yes. This is explained in the documentation as well as the FAQ.
From the FAQ:
How do I create a message with attachments?
To construct a message with attachments, the first thing you'll need to do is create a multipart/mixed container which you'll then want to add the message body to first. Once you've added the body, you can then add MIME parts to it that contain the content of the files you'd like to attach, being sure to set the Content-Disposition header value to the attachment. You'll probably also want to set the filename parameter on the Content-Disposition header as well as the name parameter on the Content-Type header. The most convenient way to do this is to simply use the MimePart.FileName property which
will set both parameters for you as well as setting the Content-Disposition header value to attachment if it has not already been set to something else.
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
Text = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday. I was hoping you could make it.
Will you be my +1?
-- Joey
"
};
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
Content = new MimeContent (File.OpenRead (path)),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);
// now set the multipart/mixed as the message body
message.Body = multipart;
A simpler way to construct messages with attachments is to take advantage of the
BodyBuilder class.
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
var builder = new BodyBuilder ();
// Set the plain-text version of the message text
builder.TextBody = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday. I was hoping you could make it.
Will you be my +1?
-- Joey
";
// We may also want to attach a calendar event for Monica's party...
builder.Attachments.Add (#"C:\Users\Joey\Documents\party.ics");
// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody ();
For more information, see Creating Messages.
#jstedfast brought pretty cool solution, here are a few more examples of simple ways to just send a file as an attachment (pdf document in this case, but can be applied to any file type).
var message = new MimeMessage();
// add from, to, subject and other needed properties to your message
var builder = new BodyBuilder();
builder.HtmlBody = htmlContent;
builder.TextBody = textContent;
// you can either create MimeEntity object(s)
// this might get handy in case you want to pass multiple attachments from somewhere else
byte[] myFileAsByteArray = LoadMyFileAsByteArray();
var attachments = new List<MimeEntity>
{
// from file
MimeEntity.Load("myFile.pdf"),
// file from stream
MimeEntity.Load(new MemoryStream(myFileAsByteArray)),
// from stream with a content type defined
MimeEntity.Load(new ContentType("application", "pdf"), new MemoryStream(myFileAsByteArray))
}
// or add file directly - there are a few more overloads to this
builder.Attachments.Add("myFile.pdf");
builder.Attachments.Add("myFile.pdf", myFileAsByteArray);
builder.Attachments.Add("myFile.pdf", myFileAsByteArray , new ContentType("application", "pdf"));
// append previously created attachments
foreach (var attachment in attachments)
{
builder.Attachments.Add(attachment);
}
message.Body = builder.ToMessageBody();
Hope it helps.
You can also send multiple files using this approach directly.
**Note: files used here is IEnumerable files **
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(emailService.FromFullName, emailService.FromEmail));
message.To.AddRange(emailsToSend.Select(x => new MailboxAddress(x)));
message.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = body;
foreach (var attachment in files)
{
if (attachment.Length > 0)
{
string fileName = Path.GetFileName(attachment.FileName);
builder.Attachments.Add(fileName, attachment.OpenReadStream());
}
}
message.Body = builder.ToMessageBody();
}
to specify the question:
I'm creating a bitmap object, which I want to send with an email. I don't want to save it before or upload it to a webserver. Just attach it and then link the attachement in the html body of the mail.
I've searched quite a time now and all I can find are answers in which the picture is stored in the file system or on a server.
So is there any way to do this whithout saving the image before?
Thanks
Edit:
I've tried around a bit and finally came to this solution:
MailMessage mail = new MailMessage();
mail.To.Add(new MailAddress("xxx#yyy.de"));
mail.From = new MailAddress("xxx#yyy.de");
SmtpClient sender = new SmtpClient
{
Host = "smtp.client",
Port = 25
};
mail.Subject = "test";
body= "blablabla<br><img alt=\"\" hspace=0 src=\"cid:ImagedId\" align=baseline border=0 ><br>blablabla";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
using (System.IO.MemoryStream image = new System.IO.MemoryStream())
{
Bitmap diagram = new Bitmap("C:\\qwer.bmp");
diagram.Save(image, System.Drawing.Imaging.ImageFormat.Jpeg);
LinkedResource resource = new LinkedResource(image, "image/jpeg");
resource.ContentId = "ImageId";
resource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(resource);
mail.AlternateViews.Add(htmlView);
sender.Send(mail);
}
But now my MailClient (Lotus Notes) doesnt open the mail with the error: "no mime data".
Any Idea how to solve this?
Try creating it in Word (either just the image or whole email) then drag over it and copy and paste into Outlook. I think that auto attaches images as well as embeds them.
I need to send a HTML content as Email, If the HTML has any image..it dosent show uo in the Email.
I cannot attach the image to the mail
The Image will be inside HTML, which i get from a CMS
How can i solve this issue ?
Are you adding image as linked resource? Here is an example how to do this: http://www.codeproject.com/Articles/34467/Sending-Email-Using-Embedded-Images
using System.Net.Mail;
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:Pic1\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
// Create a LinkedResource object for each embedded image
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
pic1.ContentId = "Pic1";
avHtml.LinkedResources.Add(pic1);
// Add the alternate views instead of using MailMessage.Body
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
// Address and send the message
m.From = new MailAddress("rizwan#dotnetplayer.com", "Rizwan Qureshi");
m.To.Add(new MailAddress("shayan#dotnetplayer.com", "Shayan Qureshi"));
m.Subject = "A picture using alternate views";
SmtpClient client = new SmtpClient("smtp.dotnetplayer.com");
client.Send(m);
In all HTML e-mails that cannot have the images attached, all images must be placed in a server and be referenced in the HTML with their full path e.g. "http://www.yourdomain.com/images/imagename.ext". Casing IS important, and it is the most common cause for images not appearing.
It works great to send emails (to Outlook) in HTML format by assigning the text/html content type string like so:
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("--#---.com");
message.ReplyTo = new MailAddress("--#---.com");
message.To.Add(new MailAddress("---#---.com"));
message.Subject = "This subject";
message.Body = "This content is in plain text";
message.IsBodyHtml = false;
string bodyHtml = "<p>This is the HTML <strong>content</strong>.</p>";
using (AlternateView altView = AlternateView.CreateAlternateViewFromString(bodyHtml,
new ContentType(MediaTypeNames.Text.Html)))
{
message.AlternateViews.Add(altView);
SmtpClient smtp = new SmtpClient(smtpAddress);
smtp.Send(message);
}
}
The email is correctly recognized as HTML in Outlook (2003).
But if I try rich text:
MediaTypeNames.RichText;
Outlook doesn't detect this, it falls back to plain text.
How do I send email in rich text format?
The bottom line is, you can't do this easily using System.Net.Mail.
The rich text in Outlook is sent as a winmail.dat file in the SMTP world (outside of Exchange).
The winmail.dat file is a TNEF message. So, you would need to create your richtext inside of the winmail.dat file (formatted to TNEF rules).
However, that's not all. Outlook uses a special version of compressed RTF, so, you would also need to compress your RTF down, before it's added to the winmail.dat file.
The bottom line, is this is difficult to do, and unless the client really, really needs this functionality, I would rethink it.
This isn't something you can do with a few lines of code in .NET.
You can also achieve this by adding another alternate view before your calendar view as below:
var body = AlternateView.CreateAlternateViewFromString(bodyHtml, new System.Net.Mime.ContentType("text/html"));
mailMessage.AlternateViews.Add(body);
This worked for me..
public void sendUsersMail(string recipientMailId, string ccMailList, string body, string subject)
{
try
{
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("norepl#xyz.com", "Tracker Tool");
Msg.To.Add(recipientMailId);
if (ccMailList != "")
Msg.CC.Add(ccMailList);
Msg.Subject = subject;
var AltBody = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
Msg.AlternateViews.Add(AltBody);
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("mail.xyz.com");
smtp.Send(Msg);
smtp.Dispose();
}
catch (Exception ex)
{
}
}