Reportviewer send email via gmail

99封情书 提交于 2019-12-11 08:17:47

问题


I am working on a WinForm where a reportviewer is embedded.

How do I send email via gmail/yahoo and attach this report as a pdf? I looked at this post http://www.codeproject.com/Articles/32109/Send-Mail-and-Print-Report-in-Report-Viewer-Contro but was not sure if it would work only with desktop email clients such as Outlook or will it support web based email client?

Thanks in advance!


回答1:


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)
  {
  }
}


来源:https://stackoverflow.com/questions/13168085/reportviewer-send-email-via-gmail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!