I'm trying to send an email and it should display subject line like below.
I tried to put image in subject line but it won't work.
I also googling but unable to find any solution.
Is anyone know how to do it ?
Thank you.
That's an Emoji.
With the coolness of emoji, a new markting boom is adding emojis to the subject lines of email.
It´s not possible to add your own custom images to the subject line.
https://www.campaignmonitor.com/resources/guides/using-emojis-and-symbols-in-email-marketing/
Creating an email message using UTF-8
https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.bodyencoding%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
List of unicode Emojis
http://unicode.org/emoji/charts/full-emoji-list.html
As you know by now, you're referencing an emoji. But I just want to share that my own experience using emojis in C# for sending gmail does not require any conversion to UTF8.
In the link provided by Webbanditten, this is presented for the sake of producing some arrows:
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test email message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
I don't know if its because I'm working on a .cs file that's saved as UTF-8 already, but I can just cut and paste emojis right in and don't have do deal with SubjectEncoding or with character codes.
A modified version of the code below runs successfully and both notepad and visual studio display the actual emoji in the code so it's 'readable'.
var hasIssues = true;
var emoji = hasIssues ? "😡" : "👍";
using (var client = new SmtpClient("host"))
using (var mail = new MailMessage()) {
mail.From = new MailAddress("name#from.com");
mail.To.Add("name#to.com);
mail.Subject = $"{emoji} Emoji Test";
mail.Body = "Did it go well? Check the emoji on the subject line";
client.Send(mail);
}
Related
I am trying to add a picture to the mail I am sending in C#, and I found some code in here - stackoverflow. (the question: Add Attachment base64 image in MailMessage and read it in html body).
but this code is giving me syntax errors in C# I don't know how to solve correctly... here is my code:
using System.Net.Mail;
using System.Net.Mime;
public static string FixBase64ForImage(string Image)
{
System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);
sbText.Replace("\r\n", string.Empty); sbText.Replace(" ", string.Empty);
return sbText.ToString();
}
public static bool SendEmail2(string mailToGet, string subject, string message, string image)
{
try
{
Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage(image));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
MailMessage mail = new MailMessage();
var imageToInline = new LinkedResource(streamBitmap, MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = "MyImage";
alternateView.LinkedResources.Add(imageToInline);//here there is an error
mail.AlternateViews.Add(body);//here there is an error
//from now on - my code:
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.IsBodyHtml = true;
message+= "<img alt ='' src ='cid: MyImage'/>";
mail.Body = message;
mail.Subject = subject;
mail.To.Add(mailToGet);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myEmailAdress", "myPassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}catch(Exception e)
{
throw e;
}
}
I have two errors: one on line alternateView.LinkedResources.Add(imageToInline);, where it says: The name 'alternateView' does not exist in the current context, and one on line mail.AlternateViews.Add(body);, where it gives the same - on the body.
I tried creating these elements here, but it only got me into more trouble... I don't even know if I am using the right usings (by the way, I put these by the demand of C#, not as part of the code I copied). Can anyone tell me what this code means and where I was wrong? and if you know, what should I do to repair this?
Firstly, your alternateView does not exist because you did not instanciate it, to do this you need to add this line before:
AlternateView alternateView = new AlternateView("MyImage");
Where "MyImage" is the name of the file. And in regards to the body error you need to add that alternating view that you just created, so instead of "body" you just need to put alternateView like so:
mail.AlternateViews.Add(alternateView);
I want to send a (view page) pdf sending by email.but when I trying to add an attachment, I found an error below "Add". for that I can't successfully sending mail with attaching my view pdf.
Here is my code:
(Ordercontroller)
//other code
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test Project", "pt300#gmail.com"));
message.To.Add(new MailboxAddress("psm", "p689#gmail.com"));
message.Subject = "Hi,this is demo email";
message.Body = new TextPart("plain")
{
Text = "Hello,My First Demo Mail it is.Thanks",
};
//add attach
var aa = new ViewAsPdf("Cart")
{
FileName = "Invoice.pdf", //actually, I don't know why this filename is
// "Invoice". I found this system on a website.
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
};
message.Attachments.Add(aa);
//end attach
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("pt300#gmail.com", "MyPassword");
client.Send(message);
client.Disconnect(true);
}
//other code
and these controller's view I trying to pdf and send by mail:
(HomeController)
public ActionResult Cart()
{
List<Product> products = HttpContext.Session.Get<List<Product>>("products");
if (products == null)
{
products = new List<Product>();
}
return View(products);
}
in OrderController I found an error.
how I will solve this problem and successfully send my view's pdf by mail.please help.
Attachments is a MimeMessage property that has no such method Add, so here comes the error. To add the attachments you should create a BodyBuilder object before, with this class you will be able to add new attachments (each one of them as byte array), usign Attachments Property and its Add method, but always related to BodyBuilder, not to MimeMessage.
Please, take a look to the answer given here, as I guess is what you are looking for:
.net Core Mailkit send attachement from array
Or check another example here:
https://www.taithienbo.com/send-email-with-attachments-using-mailkit-for-net-core/
In addition, you could get Rotativa PDF as byte array usign this code:
var rotativaAction = new ViewAsPdf("Cart")
{
FileName = "Invoice.pdf", // You can change this file name to set whatever you want
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
};
byte[] fileAttachmetByteArray = rotativaAction.BuildFile(ControllerContext);
Once you have generated your PDF as a byte array using Rotativa, guessing you have stored the result in a variable called fileAttachmentByteArray (as stated in the previous code sample), you must simply send this variable (the byte array) to the Add method of the BodyBuilder, as the second parameter (first is the attachement file name, which is completely free to use the name you prefer), and then set Mime Message Body, usign the BodyBuilder you have worked with.
So, to explain the process in steps:
On the first line you create a BodyBuilder variable, and initialize it, using the text you want as body for the email.
Then, you call Add method to add a new attachment, sending to it the file name you wish and your previously created bye array
Finally, you asign the value to the Body property of your Mime Message
And your code should look like this:
var builder = new BodyBuilder { HtmlBody = "yourBodyMessage" }; // Change "yourBodyMessage" to the email body you desire
builder.Attachments.Add("filename", fileAttachmentByteArray); // Once again, you can change this "filename" to set whatever you want
mimeMessage.Body = builder.ToMessageBody(); // Assuming mimeMessage is the same variable you provided in your code
I have iCalendar meeting requests sending correctly via SMTP (using the code below), but when I attempt to attach a file, the file does not appear as part of the iCalendar. When saving out the .ics after opening it in outlook, the whole file data has been stripped out.
Here's the code I'm using:
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new System.Net.Mail.MailAddress("test1#test.com", "test1");
msg.To.Add(new System.Net.Mail.MailAddress("test2#test.com", "test2"));
msg.Subject = "Subject1";
msg.Body = "Body line 1\r\nBody line 2\r\nBody line 3";
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
ct.Parameters.Add("method", "REQUEST");
ct.Parameters.Add("name", "meeting.ics");
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("BEGIN:VCALENDAR");
sb.AppendLine("PRODID:-/Microsoft Corporation//Outlook 15.0 MIMEDIR//EN");
sb.AppendLine("VERSION:2.0");
sb.AppendLine("METHOD:REQUEST");
sb.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE");
sb.AppendLine("BEGIN:VEVENT");
string file = "D:\\LoadedDate.xlsx";
string filename = Path.GetFileName(file);
sb.Append("ATTACH;ENCODING=BASE64;VALUE=BINARY;X-FILENAME=");
sb.Append(filename).Append(":").AppendLine(Convert.ToBase64String(File.ReadAllBytes(file), Base64FormattingOptions.InsertLineBreaks));
foreach (System.Net.Mail.MailAddress to in msg.To)
{
sb.AppendLine(String.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", String.IsNullOrEmpty(to.DisplayName) ? to.Address : to.DisplayName, to.Address));
}
sb.AppendLine("CLASS:PUBLIC");
sb.Append("CREATED:").AppendLine(DateTime.Now.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"));
sb.Append("DESCRIPTION:").Append(msg.Body.Replace("\r\n", "\\n")).Append("\\n <<").Append(filename).AppendLine(">> \\n");
string dt = DateTime.Now.AddHours(1).ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z");
sb.AppendLine("DTSTART:" + dt);
sb.AppendLine("DTSTAMP:" + dt);
sb.AppendLine("DTEND:" + DateTime.Now.AddHours(5).ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"));
sb.AppendLine("LAST-MODIFIED:");
sb.Append("LOCATION:").AppendLine("Location1");
sb.AppendLine(String.Format("ORGANIZER;CN=\"{0}\":mailto:{0}", msg.From.Address));
sb.AppendLine("PRIORITY:5");
sb.AppendLine("SEQUENCE:0");
sb.Append("SUMMARY;LANGUAGE=en-gb:").AppendLine(msg.Subject);
sb.AppendLine("TRANSP:OPAQUE");
// UID should be unique.
sb.Append("UID:").AppendLine(Guid.NewGuid().ToString());
sb.Append("X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\\n");
sb.Append("<HTML>\\n").Append("<HEAD>\\n").Append("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html\\; charset=iso-8859-1\">\\n").Append("<META NAME=\"Generator\" CONTENT=\"MS Exchange Server version 14.03.0162.000\">\\n");
sb.Append("<TITLE>").Append(msg.Subject).Append("</TITLE>\\n");
sb.Append("</HEAD>\\n").Append("<BODY>\\n").Append("<!--Converted from text/rtf format -->\\n\\n");
sb.Append("<P DIR=LTR><SPAN LANG=\"en-gb\"><FONT FACE=\"Calibri\">").Append(msg.Body.Replace("\r\n", "</FONT></SPAN></P>\\n\\n<P DIR=LTR><SPAN LANG=\"en-gb\"><FONT FACE=\"Calibri\">")).Append("</FONT></SPAN></P>\\n\\n");
sb.Append("<P DIR=LTR><SPAN LANG=\"en-gb\"><FONT FACE=\"Arial\" SIZE=2 COLOR=\"#000000\"> <\\;<\\;").Append(filename).Append(">\\;>\\; </FONT></SPAN></P>\\n\\n");
sb.Append("</BODY>\\n").AppendLine("</HTML>");
sb.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
sb.AppendLine("X-MICROSOFT-CDO-IMPORTANCE:1");
sb.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:FALSE");
sb.AppendLine("X-MS-OLK-AUTOFILLLOCATION:FALSE");
sb.AppendLine("X-MS-OLK-AUTOSTARTCHECK:FALSE");
sb.AppendLine("X-MS-OLK-CONFTYPE:0");
sb.AppendFormat("X-MS-OLK-SENDER;CN=\"{0}\":mailto:{0}", msg.From.Address).AppendLine();
sb.AppendLine("STATUS:TENTATIVE");
sb.AppendLine("BEGIN:VALARM");
sb.AppendLine("TRIGGER:-PT15M");
sb.AppendLine("ACTION:DISPLAY");
sb.AppendLine("DESCRIPTION:Reminder");
sb.AppendLine("END:VALARM");
sb.AppendLine("END:VEVENT");
sb.AppendLine("END:VCALENDAR");
System.Net.Mail.AlternateView av = System.Net.Mail.AlternateView.CreateAlternateViewFromString(sb.ToString(), ct);
msg.AlternateViews.Add(av);
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("mailserver");
client.Send(msg);
I've had a look at the RFC for iCalendars (https://www.rfc-editor.org/rfc/rfc5545), and I think I've done everything according to what the spec says. I'm guessing that there is either a problem with the way the file is read in (the Convert.ToBase64String bit), or I'm missing something with the alternate view (I've seen other people adding multiple views).
Things I have tried:
Replacing the Convert.ToBase64String(File.ReadAllBytes(file),
Base64FormattingOptions.InsertLineBreaks) with
Convert.ToBase64String(File.ReadAllBytes(file),
Base64FormattingOptions.None).
Using System.Text.Encoding
to convert the file to BASE64 (without success).
Attaching files to the email directly (using the
MailMessage.Attachments), but that just makes the email appear as a
normal email.
I've also had a look at the DDay.iCal project on sourceforge (http://sourceforge.net/projects/dday-ical/), but I couldn't figure out how that worked when it came to attaching a file.
One requirement I have for this is that the file has to be embedded / attached to the email, I cannot add it as a URI unfortunately.
Can anyone help?
Update: Following arnaudq's advice, I have implemented wrapping the lines at 75 characters as mentioned in the RFC. The resulting MIME message looks like the following:
BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 15.0 MIMEDIR//EN
VERSION:2.0
METHOD:REQUEST
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
ATTACH;ENCODING=BASE64;VALUE=BINARY;X-FILENAME=test.txt:U0ZMb2dObwlTRkxvYWR
lZERhdGUNCjkxNzY3NC8xCTI3LzExLzIwMTIgMTg6MzANCjkxMjIwNS8xCTI3LzExLzIwMTIgM
Tg6MzANCjkxMjI0Ni8xCTI3LzExLzIwMTIgMTg6MzANCjkxMjI1Mi8xCTI3LzExLzIwMTIgMTg
6MzANCjkxMjQyMS8xCTI3LzExLzIwMTIgMTg6MzANCjkxMjQyMi8xCTI3LzExLzIwMTIgMTg6M
zANCjkxNTMyMS8xCTI3LzExLzIwMTIgMTg6MzANCjkxNTQzNS8xCTI3LzExLzIwMTIgMTg6MzA
NCjkxNTU5OS8xCTI3LzExLzIwMTIgMTg6MzANCjkxNjc3NC8xCTI3LzExLzIwMTIgMTg6MzANC
jkxNjk1OS8xCTI3LzExLzIwMTIgMTg6MzANCjkxNjk2MC8xCTI3LzExLzIwMTIgMTg6MzANCjk
xNzM2Ny8xCTI3LzExLzIwMTIgMTg6MzANCjkxNzQzNC8xCTI3LzExLzIwMTIgMTg6MzANCjkxN
DczMS8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDczMi8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc
0My8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc0NC8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc0N
S8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc0Ni8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc2MS8
xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc2Mi8xCTI3LzExLzIwMTIgMTg6MzANCjkxNDc2My8xC
TI3LzExLzIwMTIgMTg6MzANCjkxNTYzNS8xCTI3LzExLzIwMTIgMTg6MzANCjkxNTYzOC8xCTI
3LzExLzIwMTIgMTg6MzANCjkxNTY0MC8xCTI3LzExLzIwMTIgMTg6MzANCjkxNTY0MS8xCTI3L
zExLzIwMTIgMTg6MzANCjkxNTY1OS8xCTI3LzExLzIwMTIgMTg6MzANCjkxNTc3Ni8xCTI3LzE
xLzIwMTIgMTg6MzANCjkxNTc3Ny8xCTI3LzExLzIwMTIgMTg6MzANCjkxNTc3OC8xCTI3LzExL
zIwMTIgMTg6MzANCg==
ATTENDEE;CN="Test 1";RSVP=TRUE:mailto:test1#test.com
CLASS:PUBLIC
CREATED:20150318T095735Z
DESCRIPTION:Body line 1
Body line 2
Body line 3
<<test.txt>>
DTSTART:20150318T105735Z
DTSTAMP:20150318T105735Z
DTEND:20150318T145735Z
LAST-MODIFIED:
LOCATION:Location1
ORGANIZER;CN="test2#test.com":mailto:test2#test.com
PRIORITY:5
SEQUENCE:0
SUMMARY;LANGUAGE=en-gb:Subject1
TRANSP:OPAQUE
UID:40306717-c29a-42d1-b03e-0240a93c2ea2
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//E
N"><HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html\; charse
t=iso-8859-1"><META NAME="Generator" CONTENT="MS Exchange Server version 1
4.03.0162.000"><TITLE>Subject1</TITLE></HEAD><BODY><!--Converted from text
/rtf format --><P DIR=LTR><SPAN LANG="en-gb"><FONT FACE="Calibri">Body lin
e 1</FONT></SPAN></P><P DIR=LTR><SPAN LANG="en-gb"><FONT FACE="Calibri"></
FONT></SPAN></P>Body line 2</FONT></SPAN></P><P DIR=LTR><SPAN LANG="en-gb"
><FONT FACE="Calibri"></FONT></SPAN></P>Body line 3<P DIR=LTR><SPAN LANG="
en-gb"><FONT FACE="Arial" SIZE=2 COLOR="#000000"> <\;<\;test.txt>\;&
gt\; </FONT></SPAN></P></BODY></HTML>
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-DISALLOW-COUNTER:FALSE
X-MS-OLK-AUTOFILLLOCATION:FALSE
X-MS-OLK-AUTOSTARTCHECK:FALSE
X-MS-OLK-CONFTYPE:0
STATUS:TENTATIVE
BEGIN:VALARM
TRIGGER:-PT15M
ACTION:DISPLAY
DESCRIPTION:Reminder
END:VALARM
END:VEVENT
END:VCALENDAR
Unfortunately, this still doesn't work and the file (in this case a simple plain text file) does not come through with the calendar entry in Outlook.
What's really interesting is that saving the above MIME message to a file manually and renaming to a .ics then opening it does display the attached file correctly. This makes me think that there is something wrong with the way I'm sending the message, instead of the iCalendar markup.
Any ideas what is wrong?
#paul, I made the following changes and its working fine for me. I need to verify this fix on all email clients. I tested on MS Outlook 2013, ios, MS Outlook 2010 and its working fine.
MailMessage msg = new MailMessage();
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
Stream stream = new MemoryStream(attachment.Bytes);// Bytes of file
LinkedResource resource = new LinkedResource(stream);
resource.ContentId = attachment.Name.Replace(".", "") + DateTime.Now.Ticks.ToString();
resource.ContentType.Name = attachment.Name;//Name of file
resource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
alternate.LinkedResources.Add(resource);
msg.AlternateViews.Add(alternate);
I am not modifying .ics file to add ATTACH property(ATTACH;ENCODING=BASE64;VALUE=BINARY;X-FILENAME=)
String iCall = CreateICal();
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
ct.Parameters.Add("charset", #"utf-8");
ct.Parameters.Add("method", "REQUEST");
AlternateView avCal = AlternateView.CreateAlternateViewFromString(iCall, ct);
System.Net.Mime.ContentType cthtml = new System.Net.Mime.ContentType("text/html");
cthtml.Parameters.Add("charset", #"utf-8");
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(this.mHTML, cthtml);
mail.AlternateViews.Add(avHtml);
mail.AlternateViews.Add(avCal);
foreach (LinkedResource resource in arrattach)
{
avHtml.LinkedResources.Add(resource);
}
client.Send(mail);
First, while you do make use of line breaks, it looks like you are not using the kind of line breaks that iCalendar expects. In short, each line after the first one should be prefixed with a space character and the lines should be less than 75 octets in length. See https://www.rfc-editor.org/rfc/rfc5545#section-3.1
(In general, for this type of interop issue, showing us the end result MIME message is more useful than the code that was used to generate it)
Then, as far as I remember, Outlook prefers attachments to be transmitted in a multipart/related containing the iCalendar stream and the attachment in different mime parts. See https://www.rfc-editor.org/rfc/rfc6047#section-4.6 for an example.
Finally, you might want to try sending an invitation with attachment from Outlook and see how the MIME message that it does send is structured.
What I want to achieve:
Scan mails and attach relevant ones to a "summary"-mail.
My problem:
I can't seem to find any information about how this is done. When using for example Outlook you can simply drag and drop a mail into another message thus attaching it. I looked through the headers and found that it's basically the mail's content and attachments with their content types attached without further encoding. But attaching this data to a MailMessage via Attachment.CreateAttachmentFromString didn't work out either, the file was displayed as a regular file.
My current code:
var mail = new MailMessage(settings.Username, to);
var smtp = new SmtpClient(settings.SMTP, settings.Port);
// ...
// authentication + packing stuff into subject and body
// ...
foreach (var att in attachments)
{
Attachment attachment = Attachment.CreateAttachmentFromString(att.Text, att.Filename);
mail.Attachments.add(attachment);
}
client.Send(mail);
client.Dispose();
mail.Dispose();
My question:
Can C# do this out of the box using some hack or are there libraries that support that?
You would probably want to just use the Attachment constructor that takes a file name:
Attachment attachment = new Attachment(att.Filename);
mail.Attachments.add(attachment);
Of course, this assumes you've saved the attachment already out to your file system somewhere.
You could also just use the attachment's content stream to avoid the overhead of saving each attachment to file first:
Attachment attachment = new Attachment(att.ContentStream, String.Empty);
mail.Attachments.add(attachment);
NOTE: the second argument to that constructor is the "content type", which, if left as an empty string, will be text/plain; charset=us-ascii. Refer to RFC 2045 Section 5.1 for more content types.
Also, see MSDN for more Attachment constructor overloads: https://msdn.microsoft.com/en-us/library/System.Net.Mail.Attachment.Attachment%28v=vs.110%29.aspx
Well, I found a way to somehow does what I needed. This solution is not the perfect answer, but it works almost as intended.
Warning
This solution requires currently Outlook installed as the mail needs to be attached as a .msg file. I want to repeat that this is not the right way to go, this method is way slower than any other solution but it works. I will further investigate soon.
But for now, here's my Extension class:
using System;
using System.Net.Mail;
using System.IO;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace MailAttachment
{
public static class Extensions
{
public static string AttachMail(this MailMessage mail, MailMessage otherMail)
{
string path = Path.GetTempPath(),
tempFilename = Path.Combine(path, Path.GetTempFileName());
Outlook.Application outlook = new Outlook.Application();
Outlook.MailItem outlookMessage;
outlookMessage = outlook.CreateItem(Outlook.OlItemType.olMailItem);
foreach (var recv in message.To)
{
outlookMessage.Recipients.Add(recv.Address);
}
outlookMessage.Subject = mail.Subject;
if (message.IsBodyHtml)
{
outlookMessage.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
outlookMessage.HTMLBody = message.Body;
}
else
{
outlookMessage.Body = message.Body;
}
outlookMessage.SaveAs(tempFilename);
outlookMessage = null;
outlook = null;
Attachment attachment = new Attachment(tempFilename);
attachment.Name = mail.Subject + ".msg";
otherMail.Attachments.Add(attachment);
return tempFilename;
}
}
}
Additional information
This solution requires you to delete the temporary file after you sent the mail. This might look like this:
MailMessage mail = new MailMessage();
List<MailMessage> mailsToAttach = mails.FindAll(m => m.Date.CompareTo(otherDate) < 0);
List<string> tempFiles = new List<string>();
foreach (var item in mailsToAttach)
{
string tempFile = mail.AttachMail(item);
tempFiles.Add(tempFile);
}
// smtp.Send(mail)
foreach (var item in tempFiles)
{
System.IO.File.Delete(item);
}
I want to dynamically create an email and send it. So far so good, the problem is that it's in dutch language and it doesn't display correctly.
I am doing this:
// Body Html
if (!string.IsNullOrEmpty(emailMessage.BodyHtml))
{
var encoding = Encoding.UTF32;
byte[] byteArray = Encoding.GetEncoding("iso-8859-1").GetBytes(emailMessage.BodyHtml);
byte[] unicodeArray = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), encoding, byteArray);
emailMessage.BodyHtml = encoding.GetString(unicodeArray);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType();
ct.MediaType = MediaTypeNames.Text.Html;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(emailMessage.BodyHtml, ct);
mailMessage.AlternateViews.Add(htmlView);
htmlView.TransferEncoding = TransferEncoding.QuotedPrintable;
}
try
{
smtpSender.Send(mailMessage);
}
The mail should contain Financiële details but when i open the mail with outlook i see Financiele details
How to fix it?
Please have a look at the InternetCodepage property of the Outlook mailitem. I had a similar issue with a new e-Mail in which I inserted text from an existiing e-mail, in which German Umlauts didn't displaying correctly. This was solved after I set the InternetCodepage in the new e-mail to the appropriate value of the original e-mail.
See http://msdn.microsoft.com/en-us/library/office/ff860730.aspx for more information about this property and a list of possible values.