I have been fighting with HTML emails with images in them. I have them working on desktop Thunderbird and Outlook, but Android Email shows a broken image.
I know it can work, because an email created with Outlook works, and has a very similar structure to the ones I am creating. Obviously it's not the same (otherwise mine would work!), but I can't see what I am missing.
I haven't cut down the code much, as I'm hoping someone will see a problem with the LinkedResource or the AlternateResource, but it might be something bigger.
The HTML view has the image tag in it, which works properly on the desktop. It shows the alternate text on Android, with a broken image icon.
Any help would be greatly appreciated.
bool SendEmail()
{
string fullBody = GenerateHeader() + Body + GenerateFooter();
string textBody = RemoveHTML(Body);
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(fullBody, Encoding.UTF8, MediaTypeNames.Text.Html);
avHtml.TransferEncoding = TransferEncoding.QuotedPrintable;
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Subject = BaseSubject + Subject;
message.Body = textBody;
message.AlternateViews.Add(avHtml);
message.AlternateViews.Add(avText);
message.Headers.Add("Message-Id",
String.Format("<{0}@{1}>",
Guid.NewGuid().ToString(),
"company.com.au"));
var assembly = Assembly.GetExecutingAssembly();
string resourceName = "app.UI.EmbeddedItems.logo.png";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
LinkedResource inline = new LinkedResource(stream, "image/png");
inline.ContentId = LogoId;
inline.ContentType.Name = "logo.png";
inline.ContentLink = new Uri("cid:" + inline.ContentId);
inline.TransferEncoding = TransferEncoding.Base64;
inline.ContentType.MediaType = "image/png";
avHtml.LinkedResources.Add(inline);
foreach (var addr in ToAddresses)
{
try
{
message.To.Add(addr);
}
catch (FormatException ex) // invalid email
{
error = ex.Message;
}
}
foreach (var att in Attachments)
{
message.Attachments.Add(att.ToAttachment());
}
if (message.To.Count > 0) // we actually added something
{
SmtpClient client = new SmtpClient();
try
{
client.Send(message);
return true;
}
catch (Exception exception)
{
error = exception.Message;
return false;
}
}
else
{
return true;
}
}
}
}
private string GenerateHeader()
{
var header = new StringBuilder();
header.Append("<html xmlns = 'http://www.w3.org/1999/xhtml'>\n");
header.Append("<head>\n");
header.Append("<meta content='en-au' http-equiv='Content-Language' />\n");
header.Append("<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />\n");
header.Append("<title>Email Notification</title>\n");
header.Append("</head>\n");
header.Append("<body>\n");
header.Append("<img id='").Append(LogoName).Append("' alt='Logo' src='cid:").Append(LogoId).Append("' />\n");
return header.ToString();
}