如何将以编程方式生成的PDF附加到电子邮件并发送?

时间:2012-05-23 20:38:43

标签: asp.net vb.net

我正在尝试阅读html文件并使用itexsharp将其转换为pdf并通过电子邮件将其作为附件发送:

这是客户端代码

<form id="form1" runat="server">
<div>
<img alt="" src="C:\Users\Intern\Documents\Visual Studio  2008\Projects\highChart\highChart\images\279.gif" id="myImg" />

</div>
</form>

服务器端代码

 Imports iTextSharp
 Imports iTextSharp.text.pdf
 Imports iTextSharp.text
 Imports System
 Imports System.Text
 Imports System.IO
 Imports System.Net.Mail
 Imports System.Net
 Imports iTextSharp.text.html.simpleparser

 Partial Public Class imagePdf
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Me.Page.RenderControl(hw)

    Dim sr As New StringReader(sw.ToString())
    Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
    Dim htmlparser As New HTMLWorker(pdfDoc)
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()
    htmlparser.Parse(sr)
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.[End]()

    Dim file As (( i don't know what to add here ))
    Dim message As New MailMessage()
    message.From = New MailAddress("testApp@somewhereelse.com")
    message.To.Add(New MailAddress("anotheraddres84@hotmail.com"))
    message.Subject = "pdf "
    message.Body = "pdf attached "
    Dim data As New Attachment(File)
    message.Attachments.Add(data)

    Dim client As New SmtpClient()
    client.Host = "smtp.gmail.com"
    client.Credentials = New NetworkCredential("email", "password")
    client.EnableSsl = True
    client.Port = 587
    client.Send(message)
End Sub

End Class

此代码的每个部分都可以正常工作,即pdf有效,电子邮件很好,但我如何使用pdf文件作为我的附件?

2 个答案:

答案 0 :(得分:3)

将PDF存储为文件,然后使用MailMessage.Attachments属性将其添加到邮件中。

答案 1 :(得分:1)

您可以拥有完整路径,如下所示:c:\ asdasd \ adad \“+ filename.pdf

或者您使用Server.MapPath(“/ subdir / filename.pdf”);

Server.MapPath为您提供当前目录,即您已经在的目录。

相关问题