1

我正在开发一个嵌入了报表查看器的 WinForm。

如何通过 gmail/yahoo 发送电子邮件并将此报告附加为 pdf?我查看了这篇文章 http://www.codeproject.com/Articles/32109/Send-Mail-and-Print-Report-in-Report-Viewer-Contro但不确定它是否仅适用于桌面电子邮件客户端等作为 Outlook 还是支持基于 Web 的电子邮件客户端?

提前致谢!

4

1 回答 1

0
const string HTML_TAG_PATTERN = "<.*?>";
static string StripHTML(string inputString)
{
  return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty);
}

public static void sendMessage()
{
  var username = "john.doe@gmail.com";
  var password = "password";
  MailAddress MailFrom = new MailAddress("john.doe@gmail.com");
  MailAddress MailTo = new MailAddress("john.doe@gmail.com");
  var subject = "TEST SUBJECT";
  var attachmentPath = "test.pdf";
  var mailBody = "<b>test</b>";


  NetworkCredential cred = new NetworkCredential(username, password);

  System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
  smtp.Host = "smtp.gmail.com";
  smtp.UseDefaultCredentials = false;
  smtp.EnableSsl = true;
  smtp.Credentials = cred;
  smtp.Port = 587;

  MailMessage mail = new MailMessage();

  mail.IsBodyHtml = true;

  AlternateView avAlternateView = null;
  Encoding myEncoding = Encoding.GetEncoding("UTF-8");

  avAlternateView = AlternateView.CreateAlternateViewFromString(StripHTML(mailBody), myEncoding, "text/plain");
  mail.AlternateViews.Add(avAlternateView);

  avAlternateView = AlternateView.CreateAlternateViewFromString(mailBody, myEncoding, "text/html");
  mail.AlternateViews.Add(avAlternateView);

  mail.Sender = MailFrom;
  mail.From = MailFrom;
  mail.ReplyTo = MailFrom;

  mail.To.Add(MailTo);

  mail.Subject = subject;
  mail.SubjectEncoding = Encoding.GetEncoding("UTF-8"); 

  mail.BodyEncoding = Encoding.GetEncoding("UTF-8");

  Attachment attachment = new Attachment(attachmentPath);
  mail.Attachments.Add(attachment);
  try
  {
    smtp.Send(mail);
  }
  catch (Exception ex)
  {
  }
}
于 2012-10-31T22:16:09.547 回答