我们如何将gridview导出为pdf并作为邮件附件发送

时间:2015-02-23 07:10:29

标签: asp.net itextsharp

using (StringWriter sw = new StringWriter())
{
    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
        gridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();


            MailMessage mm = new MailMessage("sender.com", "bharathidasan3010@gmail.com");// error here please help me
            mm.Subject = "GridView Exported PDF";
            mm.Body = "GridView Exported PDF Attachment";
            mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "GridViewPDF.pdf"));
            mm.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName = "youarethepower@gmail.com";
            NetworkCred.Password = "<password>";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
        }
    }
}

==========================================
error : The specified string is not in the form required for an e-mail address.`

1 个答案:

答案 0 :(得分:0)

这很明显很明显。

您正在使用的System.Net.MailMessage的构造函数接受2个字符串,它正在尝试将其解析为有效的电子邮件地址。 sender.com不是有效的电子邮件格式。

将其更改为name@sender.com