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.
Related
I want to send mails with images in them. The code I've written works fine, but for some reason unknown to me it wont work with Outlook clients.
The test mail I sent was (left: Thunderbird, right: Outlook):
What my code is supposed to do is: It takes the RTF from a RichTextBox and converts it to HTML. This leaves the images embedded in the HTML as base64 strings. I extract all base64 encoded images one by one and put them into a MemoryStream which is accepted by LinkedResource. Since mail clients usually don't accept embedded images I replace the embedded image in the HTML with a content-id. Then I set some properties of LinkedResource and add it to an AlternateView. This alternate view is then added to a System.Net.Mail.MailMessage and the mail is sent.
The corresponding code:
MemoryStream mem = null;
private readonly Regex embeddedImageRegex = new Regex("src=\"data:image/.*?\"");
public MyHTMLMailMessage()
: base()
{
this.SubjectEncoding = Encoding.UTF8;
this.BodyEncoding = Encoding.UTF8;
this.IsBodyHtml = true;
}
public bool Send()
{
// create HTML View with images
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(HTML, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
ReplaceEmbeddedImagesWithCID(htmlView);
this.AlternateViews.Add(htmlView);
this.Body = HTML;
SmtpClient client = new SmtpClient(server, port);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = String.IsNullOrEmpty(username);
try
{
client.Send(this);
return true;
}
catch (SmtpException e)
{
return false;
}
finally
{
mem?.Close();
}
}
private void ReplaceEmbeddedImagesWithCID(AlternateView altView)
{
string extension;
int imageIndex = 0;
string contentID = $"image{imageIndex}";
// go through every base64 string, create a content id and LinkedResource for it
while (embeddedImageRegex.IsMatch(HTML))
{
extension = new Regex("image/.*?;").Match(HTML).Value
.Replace("image/", "")
.Replace(";", "");
string base64img = embeddedImageRegex.Match(HTML).Value
.Replace("src=\"", "")
.Replace("\"", "")
.Split(',')[1];
HTML = embeddedImageRegex.Replace(HTML, $"src=\"cid:image{imageIndex}\"", 1);
byte[] byBitmap = Convert.FromBase64String(base64img);
mem = new MemoryStream(byBitmap);
mem.Position = 0;
LinkedResource linkedImage = new LinkedResource(mem, $"image/{extension}");
linkedImage.ContentId = contentID;
altView.LinkedResources.Add(linkedImage);
altView = AlternateView.CreateAlternateViewFromString(HTML, null, MediaTypeNames.Text.Html);
imageIndex++;
}
}
So I went through different solutions but none of them worked.
My steps so far:
I edited some registration keys in HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\x.0\Outlook\Options\Mail or HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\x.0\Common
I left the image as base64 string in the HTML
There were some properties added
linkedImage.TransferEncoding = TransferEncoding.Base64;
linkedImage.ContentType.Name = contentID;
linkedImage.ContentLink = new Uri($"cid:{contentID}");
this.Headers.Add("Content-ID", $"<image{imageIndex}>");
this.Headers.Add("X-Attachment-Id", $"image{imageIndex}");
altView.TransferEncoding = TransferEncoding.QuotedPrintable;
None of this worked for me even although it seemed to help others. Did i overlook something?
Base64 images are blocked by default in Outlook.
You need to attach images to the email and set the PR_ATTACH_CONTENT_ID property on the email (the DASL name is "http://schemas.microsoft.com/mapi/proptag/0x3712001E"). See Embed Images in New Messages using a Macro for more information.
Have you confirmed it is not an image block from Trust Center Settings.
Unblock image downloads for a single message:
Click the InfoBar at the top of the message.
Click Download Pictures.
Unblock image downloads for all messages:
Outlook 2007
On the "Tools" menu, click Trust Center > Automatic Download.
Uncheck the "Don't download pictures automatically in HTML e-mail messages or RSS items" check box.
Outlook 2010 and Up:
On the "File" tab, click Options > Trust Center.
Under Microsoft Outlook Trust Center, click Trust Center Settings.
Uncheck the "Don't download pictures automatically in HTML e-mail messages or RSS items" check box.
Unblock picture downloads for all messages from a particular email address or domain:
In an open message that was sent from a particular email address or domain, right-click on a blocked item.
Do one of the following:
Click Add Sender to Safe Senders List.
Click Add the Domain [#domain] to Safe Senders List.
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
This seems like a tough one to find a good answer to. I want to create a mail message, add attachments to it, encrypt it using a X509Certificate2 certificate, and then send it. Sounds simple enough, right?! I use asp.net mvc and C#.
This is what I have so far.
string sMTPClient = ConfigurationManager.AppSettings.Get("SMTPClient");
using (var smtpClient = new SmtpClient(sMTPClient))
{
var attachments = MethodToCreateMailAttachments(......);
X509Certificate2 certificate = MethodToGetCertificateBySerialNumber("xxxxxxx");
using (var finalMailmessage = new MailMessage())
{
var encryptedMailMessage = new MailMessage();
var encryptCert = new X509Certificate2(certificate);
encryptedMailMessage.Subject = mailsubject;
encryptedMailMessage.Body = mailBody;
if (attachments.Any())
{
foreach (var item in attachments)
encryptedMailMessage.Attachments.Add(item);
}
byte[] encryptedBodyBytes = Encoding.ASCII.GetBytes(encryptedMailMessage.ToString());
EnvelopedCms Envelope = new EnvelopedCms(new ContentInfo(encryptedBodyBytes));
CmsRecipient Recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, encryptCert);
Envelope.Encrypt(Recipient);
byte[] EncryptedBytes = Envelope.Encode();
//Attach the encrypted message as an alternate view.
MemoryStream ms = new MemoryStream(EncryptedBytes);
AlternateView av = new AlternateView(ms, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
finalMailmessage.AlternateViews.Add(av);
finalMailmessage.From = new MailAddress(mailFrom);
foreach (var address in mailTo.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
finalMailmessage.To.Add(address);
}
var smtp = new SmtpClient(sMTPClient);
smtp.Send(finalMailmessage);
finalMailmessage.Dispose();
ErrorLogging.log.Debug("Mailmessage sent");
return "";
}
}
What this does is create two MailMessages, one for the things that need to be encrypted, attachments, body and subject. Then I create the message that will be sent. To this I add the first message as an alternate view. This works so far as to encrypt and send the email, and on the recieving end, I get an email with a padlock icon in Outlook.
I can then open the message in Outlook, by importing the certificate. This works. However, next to the padlock icon, in Outlook, I get the attachment paperclip icon, which suggests that there is something attached to the message. But the message is empty. So nothing gets attached apparently. I suspect the adding of the encrypted MailMessage as an alternate view to the other MailMessage, is where I have gone wrong.
I've tried a lot of other things with no luck, and this is the closest I have come to a working solution. I need some input, so does anyone have any suggestions?
I found a working solution. The problem was this part:
byte[] encryptedBodyBytes = Encoding.ASCII.GetBytes(encryptedMailMessage.ToString());
I had to create a memorystream, which can then be converted into a byte array. I used a tool called "MimeKit", which can be installed as a nuget package.
So, instead I have:
var memStream = new MemoryStream();
var mimeMessage = MimeMessage.CreateFromMailMessage(encryptedMailMessage);
mimeMessage.WriteTo(memStream);
var messageString = Encoding.UTF8.GetString(memoryStream.ToArray());
byte[] encryptedBodyBytes = Encoding.ASCII.GetBytes(messageString);
The rest is the same.
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.
I've had some success encoding the RTFbody from a MailItem using UTF8Encoding. I'm able to compose a new email, do all the new-email stuff and click send. Upon hitting send, I append the email with a tag that is also added to the categories. This all works and all through the RTFBbody.
The problem comes when I reply to RTF emails, which, for testing purposes, are just the emails I sent to my lonesome self. When I send the reply email and new tags were added, I remove the old tags first and then add the new tags. When I set the RTFBody in the reply email with the edited string that contains the new tags, I get a "not enough memory or disk space" error. This doesn't happen when I just remove the tags with the same function.
Bellow is the code I'm using:
private void ChangeRTFBody(string replaceThis, string replaceWith)
{
byte[] rtfBytes = Globals.ThisAddIn.email.RTFBody as byte[];
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
string rtfString = encoding.GetString(rtfBytes);
rtfString = rtfString.Replace(replaceThis, replaceWith);
rtfBytes = encoding.GetBytes(rtfString);
Globals.ThisAddIn.email.RTFBody = rtfBytes; < // The error is here only on
// reply and only when I replace
// with new tags
}
These are the calls I make:
Delete old tag: ChangeRTFBody(lastTag, "");
Add new tag: ChangeRTFBody("}}\0", newTag + "}}\0");
Like I said, This works when I create a new email and send it, but not when I try to reply to the same email. It also seems that the size of the byte[] almost doubles after the delete. When I check it during the Delete it's at about 15k bytes and when I check during the Add it jumps to over 30k bytes. When I try to add the newly inflated byte[] to the rtfBody is when I get the error.
Thanks for any help and tips and sorry about all the reading.
I had the same problem and came across what I think is an easier way to replace text in a outlook rtf body by using the Word.Document object model. You will need to add reference of Microsoft.Office.Interop.Word to your project first.
then add using
using Word = Microsoft.Office.Interop.Word;
then your code would look like
Word.Document doc = Inspector.WordEditor as Word.Document;
//body text
string text = doc.Content.Text;
//find text location
int textLocation = text.IndexOf(replaceThis);
if(textLocation > -1){
//get range
int textLocationEnd = textLocation + replaceThis.Length;
//init range
Word.Range myRange = doc.Range(textLocation , textLocationEnd);
//replace text
myRange.Text = replaceWith
}