如何将电子邮件作为MSG文件附加到CRM 2011中的外发电子邮件中?
我已经创建了电子邮件的html附件,但是必须在浏览器中查看html附件; Outlook中的预览不显示图像。
我遇到的问题是CRM中的ActivityMimeAttachment实体要求正文为Base64字符串,如果它是一个html字符串作为附件就可以了:
// UnicodeEncoding had to be used as there were problems with
// special char in ASCII
var bodyArray = System.Text.UnicodeEncoding.Unicode.GetBytes(body);
body = System.Convert.ToBase64String(bodyArray);
return body;
如何使用从System.Net.Mail.MailMessage
创建的MSG文件作为附件,或者如何将System.Net.Mail.MailMessage
电子邮件转换为Base64String?
答案 0 :(得分:0)
我找到了这个codeproject article
使用反射通过非公共的MailWriter类型保存它。这种方式很脏,但是除了in this answer
所描述的官方方式之外public static class MailMessageExt
{
public static void Save(this MailMessage Message, string FileName)
{
Assembly assembly = typeof(SmtpClient).Assembly;
Type _mailWriterType =
assembly.GetType("System.Net.Mail.MailWriter");
using (FileStream _fileStream =
new FileStream(FileName, FileMode.Create))
{
// Get reflection info for MailWriter contructor
ConstructorInfo _mailWriterContructor =
_mailWriterType.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new Type[] { typeof(Stream) },
null);
// Construct MailWriter object with our FileStream
object _mailWriter =
_mailWriterContructor.Invoke(new object[] { _fileStream });
// Get reflection info for Send() method on MailMessage
MethodInfo _sendMethod =
typeof(MailMessage).GetMethod(
"Send",
BindingFlags.Instance | BindingFlags.NonPublic);
// Call method passing in MailWriter
_sendMethod.Invoke(
Message,
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new object[] { _mailWriter, true },
null);
// Finally get reflection info for Close() method on our MailWriter
MethodInfo _closeMethod =
_mailWriter.GetType().GetMethod(
"Close",
BindingFlags.Instance | BindingFlags.NonPublic);
// Call close method
_closeMethod.Invoke(
_mailWriter,
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new object[] { },
null);
}
}
}
然后
MailMessage _testMail = new MailMessage();
_testMail.Body = "This is a test email";
_testMail.To.Add(new MailAddress("email@domain.com"));
_testMail.From = new MailAddress("sender@domain.com");
_testMail.Subject = "Test email";
_testMail.Save(@"c:\testemail.eml");
var bytes = System.IO.File.ReadAllBytes(@"c:\testemail.eml");
var bodyArray = System.Text.UnicodeEncoding.Unicode.GetBytes(bytes);
var body = System.Convert.ToBase64String(bodyArray);