需求: 点发送邮件按钮的时候, 自动在客户端电脑打开默认邮件的窗口,并且把内容和附件都附加上去.
解决方案: 尝试使用过Microsoft.Office.Interop.Outlook 和 MPAI.dll 都无法实现, 在本地debug的时候是完全没问题的, 但是部署到IIS上后发现 这两个方式都会在服务器上寻找默认的邮件客户端. 显然这个不能实现的。
Mailto :方法可行, 也可以打开默认的邮件客户端,但是无法添加附件。
最后只能在Controller里面生成EML文件
注意: 在这里我曾使用过MomeyStream 直接作为附件, 但是提示文件损坏. 后面没有时间就没有继续研究了,. 目前是保存到服务器的一个文件夹里面.
下面是实现的代码:
Helper:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Mail; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace AgilityNorthAsiaPlatform.Code.Helpers { public class MailHelper { public static void ToEmlStream(System.Net.Mail.MailMessage msg, Stream str, string dummyEmail) { using (var client = new SmtpClient()) { var id = Guid.NewGuid(); var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name); tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp"); // create a temp folder to hold just this .eml file so that we can find it easily. tempFolder = Path.Combine(tempFolder, id.ToString()); if (!Directory.Exists(tempFolder)) { Directory.CreateDirectory(tempFolder); } client.UseDefaultCredentials = true; client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; client.PickupDirectoryLocation = tempFolder; client.Send(msg); // tempFolder should contain 1 eml file var filePath = Directory.GetFiles(tempFolder).Single(); // create new file and remove all lines that start with 'X-Sender:' or 'From:' string newFile = Path.Combine(tempFolder, "modified.eml"); using (var sr = new StreamReader(filePath)) { using (var sw = new StreamWriter(newFile)) { string line; while ((line = sr.ReadLine()) != null) { if (!line.StartsWith("X-Sender:") && !line.StartsWith("From:") && // dummy email which is used if receiver address is empty !line.StartsWith("X-Receiver: " + dummyEmail) && // dummy email which is used if receiver address is empty !line.StartsWith("To: " + dummyEmail)) { sw.WriteLine(line); } } } } // stream out the contents using (var fs = new FileStream(newFile, FileMode.Open)) { fs.CopyTo(str); } } } public static string ReadSignature() { string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\Microsoft\Signatures"; string signature = string.Empty; DirectoryInfo diInfo = new DirectoryInfo(appDataDir); if (diInfo.Exists) { FileInfo[] fiSignature = diInfo.GetFiles("*.htm"); if (fiSignature.Length > 0) { StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default); signature = sr.ReadToEnd(); if (!string.IsNullOrEmpty(signature)) { string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty); signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/"); } } } return signature; } } }
Controller
public FileStreamResult ModalSendMail() {
var report = new rpt_CFS_ShipmentReport_1(); report.ajs_Param.Value = (string)LocalViewData["SendMail_Json"]; report.as_Table.Value = "Con_Shp"; report.as_UsrID.Value = User.Identity.Name; var ReportStream = new MemoryStream(); report.ExportToPdf(ReportStream); string ls_filename = "Shipment Report" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; try { report.ExportToPdf(ReportStream); FileStream fs = null; fs = new FileStream(Path.Combine(Server.MapPath("~/FileUploads/"), ls_filename), FileMode.CreateNew); fs.Write(ReportStream.GetBuffer(), 0, ReportStream.GetBuffer().Length); fs.Flush(); fs.Close(); ReportStream.Flush(); ReportStream.Close(); } catch (Exception ex) { } string dummyEmail = User.Identity.Name+"@xxx.com"; var mailMessage = new MailMessage(); mailMessage.To.Add(new MailAddress("xxx@xxx.com")); mailMessage.From = new MailAddress(dummyEmail); mailMessage.Subject = "Test subject"; mailMessage.IsBodyHtml = true; mailMessage.Body = "Test body" + MailHelper.ReadSignature(); // mark as draft mailMessage.Headers.Add("X-Unsent", "1"); // download image and save it as attachment using (var httpClient = new HttpClient()) { //download file from HTTP: //var imageStream = await httpClient.GetStreamAsync(new Uri(Path.Combine(Server.MapPath("~/FileUploads/"), ls_filename))); //mailMessage.Attachments.Add(new Attachment(HttpContext.Server.MapPath("~/App_Data/Test.docx"))); mailMessage.Attachments.Add(new System.Net.Mail.Attachment(Path.Combine(Server.MapPath("~/FileUploads/"), ls_filename), MediaTypeNames.Application.Pdf)); } var stream = new MemoryStream(); MailHelper.ToEmlStream(mailMessage, stream, "jahe@agility.com"); stream.Position = 0; return File(stream, "message/rfc822", "test_email.eml"); }