I am already successfully sending emails via the api. I now need to try and embed an image to the footer of the email.
I am running a wpf c# app and have loaded the image to my system and set it as content build type so I can get a handle on it.
The api requires a string as the body.
I have created an HTML email format via the stringbuilder class.
I am using the following code to try and embed the image.
sb.Append("<p style=\"text-align: left;\"> </p>");
var avHtml = AlternateView.CreateAlternateViewFromString(sb.ToString(), null, MediaTypeNames.Text.Html);
string path = Environment.CurrentDirectory + #"\images\fordEmail.jpg";
var inline = new LinkedResource(path, MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
sb.Append(String.Format(#"<img src=""cid:{0}"" />", inline.ContentId));
return sb.ToString();
The image appears on the email but as a dead link, red cross.
I'm not sure if I have to attach the image first or maybe render out to base64?
Any help would be gratefully accepted.
Thanks Scott
EDIT:
Code for API
mail.Subject = subject;
mail.Body = new ItemBody() { Content = body, ContentType = BodyType.HTML };
await client.Me.SendMailAsync(mail, true);
EDIT
Jason seems to be getting me along the right route. But I read somewhere that it may need saving as a draft and then sending.
My mail api code is as follows;
mail.Subject = subject;
mail.Body = new ItemBody() { Content = body, ContentType = BodyType.HTML };
await client.Me.Messages.AddMessageAsync(mail);
var messageId = mail.Id;
string path = Environment.CurrentDirectory + #"\images\fordEmail.jpg";
Image img = Image.FromFile(path);
byte[] arr;
using (var ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg);
arr = ms.ToArray();
}
mail.Attachments.Add(new FileAttachment()
{
IsInline = true,
ContentBytes = arr,
Name = "fordEmail.jpg",
ContentId = "my_inline_attachment"
});
await client.Me.Messages[messageId].SendAsync();
and the page content (as requested)
<p><strong>Automated message from xxx.</strong></p><p>*Amendment from previous notification</p><style type="text/css">.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 50px 10px 10px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#669;background-color:#e8edff;border-top-width:1px;border-bottom-width:1px;}.tg th{font-family:Arial, sans-serif;font-size:14px;text-align-left;font-weight:normal;padding:10px 50px 10px 10px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#039;background-color:#b9c9fe;border-top-width:1px;border-bottom-width:1px;}p {font-family:Arial, sans-serif;font-size:12px}p.padding {padding-right: 50px}p.smallFont {font-size:9px}</style><p>Flight xxx has now arrived. Please find the details below; </p><table class="tg"><tr><th class="tg-031e" colspan="2" text-alight:left>Flight Details</th></tr><tr><td class="tg-031e"<p>Date</p></td><td class="tg-031e"<p class="DecimalAligned">07/05/2015</p></td></tr><tr><td class="tg-031e"<p>Flight</p></td><td class="tg-031e"<p class="DecimalAligned">xxx469J</p></td></tr><tr><td class="tg-031e"<p>Route</p></td><td class="tg-031e"<p class="DecimalAligned">DUB - FNC</p></td></tr><tr><td class="tg-031e"<p class="padding">Scheduled / Actual Time Departure</p></td><td class="tg-031e"<p class="DecimalAligned">07:10 / 12:00 (UTC)</p></td></tr><tr><td class="tg-031e"<p>Scheduled / Actual Time Arrival</p></td><td class="tg-031e"<p class="DecimalAligned">10:55 / 14:00 (UTC)</p></td></tr><tr><td class="tg-031e"<p>TOB</p></td><td class="tg-031e"<p class="DecimalAligned">100+1</p></td></tr></tbody></table><p class="smallFont"><em>Source: xxx</em></span></p><p>Comments : TEST </p><p>Should you require any further information please do not hesitate to contact us </p><p>Operations Manager<br>xxx<br>t +44 (0) 111 111 111 – H24<br>s xxx<br>e xxx</p><p style="text-align: left;"> </p><img src="cid:my_inline_attachment" />
Still no attachment.
Thanks
Yes, you have to attach the file, and be sure to set IsInline to true and the ContentId property to the same value you use in the HTML markup. See this post for the raw REST equivalent: How do I send Email with inline Attachments.
OK. I found the answer with the help of this stock overflow question.
Here
The key to this is the
// Update with attachments
await m.UpdateAsync();
// Send the message
await m.SendAsync();
Seems a problem with the API at the moment. Thanks for all your help on this. Hopefully this will help others out.
Scott
Related
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
I need to send e-mails to iPhone users with .vcf files for adding contacts. The problem is that contact name has umlaut symbols and they displays incorrectly.
Also I noticed that if I send the same text in the body of email or open composed vcf file in notepad the symbols displays correctly.
public void SendEmail(string to, string subject, string body)
{
using (var message = new MailMessage())
{
message.To.Add(new MailAddress(to));
message.Subject = subject;
message.SubjectEncoding = Encoding.UTF8;
message.BodyEncoding = Encoding.UTF8;
message.HeadersEncoding = Encoding.UTF8;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
{
string attachamentName = string.Format("{0}.vcf", subject);
Attachment attachment = new Attachment(stream, MediaTypeNames.Application.Octet) { Name = attachamentName };
attachment.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
using (var client = new SmtpClient())
{
client.Send(message);
}
}
}
}
Can someone please help me?
UPDATE: Sorry, have to edit code sample, I've accidentally submit the wrong one.
UPDATE #2: It looks like it is not only iPhone problem, Outlook also does not recognize umlauts.
UPDATE #3: Added full code for sending e-mail
Try changing to:
BEGIN:VCARD\r\nVERSION:2.1\r\nN;CHARSET=LATIN1:Fältskog;Agnetha\r\nFN;CHARSET=LATIN1:Agnetha Fältskog\r\nORG:\r\nTITLE:\r\nEND:VCARD
Just from reading elsewhere - looks like the format needs this CHARSET tag on each field, and seems that either LATIN1 or iso-8859-1 character sets, rather than utf-8 need to be specified for these.
Try to change
VERSION:2.1\r\n
to
VERSION:3.0\r\n
After that you don't need CHARSET-Tags for fields with umlauts,
it should work as expected.
I'm using MailChimp for .NET from this nuget https://www.nuget.org/packages/mcapi.net/1.3.1.3 and tried sending emails. But the email I received include image (unseen image) even if I'm just sending simple html. Has anyone encountered it? How to get rid of this unseen image? Please help.
Below is my sample email message.
var api = new MandrillApi("XXXXXXXXXXX");
var recipients = new List<Mandrill.Messages.Recipient>();
var name = string.Format("{0} {1}", "Jobert", "Enamno");
recipients.Add(new Mandrill.Messages.Recipient("recipient#gmail.com", name));
var message = new Mandrill.Messages.Message()
{
To = recipients.ToArray(),
FromEmail = "admin#mysite.com",
Subject = "Test Email",
Html = "<div>Test</div>"
};
MVList<Mandrill.Messages.SendResult> result;
result = api.Send(message);
Received Email
When clicked No image shown
You're seeing this because Mandrill uses a small invisible graphic for open tracking. You'd want to either disable open tracking in the API call you're making or on the Sending Options page in your Mandrill account.
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 use free .net library to read email and I release: If I want to view body message, all free .net email library download body message and attachments. If attachments have a big size, I wait for a long time. Example: I use AE.NET.Mail to read the lastest email:
var dt = DateTime.Now;
Console.WriteLine(dt.ToLongTimeString());
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
var ic = new ImapClient("imap.gmail.com", "yourEmail", "yourPassword",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
var mailCount = ic.GetMessageCount();
ic.SelectMailbox("INBOX");
var message = ic.GetMessage(mailCount - 1);
var body = message.Body;
Console.WriteLine(body);
ic.Disconnect();
ic.Dispose();
Console.WriteLine(DateTime.Now.ToLongTimeString());
Console.WriteLine((DateTime.Now - dt).TotalSeconds);
result: 478,6s with attachment size 23mb.
How can I do if I want to view only body message with fastest speed?
I am giving you link please follow it and try another open source mail library It helps you to consume less time . TRY THIS Then put the code as shown below
MailRepository rep = new MailRepository("imap.gmail.com", 993, true, #"username", "password");
foreach (ActiveUp.Net.Mail.Message email in rep.GetUnreadMails("Inbox"))
{
System.Web.HttpContext.Current.Response.Write(string.Format("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text));
}