Skip to main content
 首页 » 编程设计

c#之如何使用内存流将 WinForms 应用程序中的 MS Chart 插入到 Outlook 电子邮件中

2024年04月30日40webabcd

我正在尝试将 MS 图表放入 outlook 电子邮件中。我想避免将它保存到桌面上,所以我决定使用 MemoryStream。到目前为止,这是我放在一起的:

MemoryStream s = new MemoryStream(); 
chart1.SaveImage(s, ChartImageFormat.Png); 
s.Position = 0; 
 
OutlookApp outlookApp = new OutlookApp(); 
MailItem mailItem = outlookApp.CreateItem(OlItemType.olMailItem); 
 
mailItem.Subject = "This is the subject"; 
chart1.SaveImage(s, ChartImageFormat.Png); 
chart1.SaveImage(s, ChartImageFormat.Png); 
mailItem.HTMLBody = "<html><body>This is the <strong>funky</strong> message body</body></html>" ; 
 
 
mailItem.Attachments.Add(s); 
 
//Set a high priority to the message 
mailItem.Importance = OlImportance.olImportanceHigh; 
mailItem.To = "testemail@gmail.com"; 
mailItem.Display(false); 
//mailItem.Send(); 

我似乎无法找到将 MemoryStream 放入电子邮件的方法。

请您参考如下方法:

Outlook 支持使用 SMTP 发送电子邮件。所以你可以使用 SmtpClient发送电子邮件。然后您可以将图片作为附件发送或将图片放在电子邮件正文中:

var body = @"Here is the chart: <br/> <img src=""$CONTENTID1$""/>"; 
var CONTENTID1 = Guid.NewGuid().ToString().Replace("-", ""); 
body = body.Replace("$CONTENTID1$", "cid:" + CONTENTID1); 
var htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); 
var stream = new MemoryStream(); 
this.chart1.SaveImage(stream, System.Drawing.Imaging.ImageFormat.Png); 
stream.Position = 0; 
LinkedResource imagelink1 = new LinkedResource(stream, "image/png"); 
imagelink1.ContentId = CONTENTID1; 
imagelink1.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; 
htmlView.LinkedResources.Add(imagelink1); 
 
MailMessage mail = new MailMessage(); 
mail.From = new MailAddress("someone@outlook.com"); 
mail.To.Add(new MailAddress("someone@example.com")); 
mail.Subject = "Subject"; 
mail.AlternateViews.Add(htmlView); 
SmtpClient client = new SmtpClient(); 
 
client.Host = "smtp-mail.outlook.com"; 
client.Port = 587; 
client.EnableSsl = true; 
client.DeliveryMethod = SmtpDeliveryMethod.Network; 
client.UseDefaultCredentials = false; 
client.Credentials = new NetworkCredential("someone@outlook.com", "password"); 
client.Send(mail); 

这样,图表图像将显示在电子邮件正文中: