Reputation: 29
I've this method to send email with images embedded in a body text and it works in almost all clients, except in Outlook. It doesn't show the images outlook but it does in outlook web. Someone help? The images are in on directory called images here you have the method
public static void SendNotificationMail(string subject, string message, string emailTo, string ccTo, string bccTo, string filename)
{
try
{
// Create a message and set up the recipients.
MailMessage msg = new MailMessage();
msg.From = new MailAddress(AppConfig.EmailFrom, AppConfig.EmailFromDisplayName);
msg.To.Add(emailTo);
if (!string.IsNullOrEmpty(ccTo))
{
msg.CC.Add(ccTo);
}
if (!string.IsNullOrEmpty(bccTo))
{
msg.Bcc.Add(bccTo);
}
msg.Subject = subject;
msg.Body = message;
String imagesPath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "images";
String[] files = Directory.GetFiles(imagesPath);
foreach(String imageFile in files){
FileInfo file = new FileInfo(imageFile);
// create the INLINE attachment
Attachment inline = new Attachment(file.FullName);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = "@"+file.Name;
inline.ContentType.MediaType = "image/jpg";
inline.ContentType.Name = Path.GetFileName(imageFile);
msg.Attachments.Add(inline);
contentID);
}
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient(AppConfig.SMTPServer);
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
Utility.PrintMessage("Sending notification e-mail to: " + emailTo);
client.Send(msg);
Logger.WriteTNSLog(subject + " - " + emailTo);
}
catch (Exception e)
{
Logger.WriteAppLog(e.Message, "Utility.SendNotificationMail()");
}
}
catch (Exception)
{
}
}
Upvotes: 0
Views: 1632
Reputation: 841
(I got this same issue trying to embed a file in an email body... In the end I had to put the Image in a byte array, and go from there:)
As I said, put your image raw data in a Byte Array imageByteArray
, and image filename (with extension) in a String imageName
. Then, attach it like this (I chose imageCid arbitrarily as the 'cid' for the attachment)
...
mail.Body = "<html><body><div style='text-align:center'><img src=""cid:imageCid"" style=""margin:0 auto;""/></body></html>";
mail.Attachments.Add(New Attachment(New MemoryStream(imageByteArray), imageName));
mail.Attachments(0).ContentId = "imageCid";
...
smtp.Send(mail);
I'm more a VB guy, so maybe you have to change it a bit. Anyways, I think I made it understandable :)
Upvotes: 1