我如何用PDF文件发送邮件

时间:2013-02-07 07:28:23

标签: c# asp.net email attachment

我想用C#发送带有邮件的pdf文件。我知道如何发送邮件,但我不知道如何用pdf文件发送邮件:(

例如,我在文件夹C:\ test.pdf

中有一个pdf文件

这是我的代码:

private void SendEmail(string pdfpath,string firstname, string lastname, string title, string company, string mailfrom,string mailto) 
{
    try
    {
        MailMessage m = new MailMessage();
        System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();

        m.From = new System.Net.Mail.MailAddress(mailfrom);
        m.To.Add(mailto);

        m.Subject = "Company Gastzugang (" + lastname + ", " + firstname + ")";


        // what I must do for sending a pdf with this email 

        m.Body = "Gastzugangdaten sind im Anhang enthalten";

        sc.Host = SMTPSERVER; // here is the smt path

        sc.Send(m);
    }
    catch (Exception ex)
    {
        error.Visible = true;
        lblErrorMessage.Text = "Folgender Fehler ist aufgetreten: " + ex.Message;
    }
}

4 个答案:

答案 0 :(得分:4)

你可以这样做:

var filename = @"c:\test.pdf";
m.Attachments.Add(new Attachment(filename));

答案 1 :(得分:2)

您需要将其添加为附件。

查看有关此问题的MSDN文档 - http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments.aspx

答案 2 :(得分:1)

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("filename");
m.Attachments.Add(attachment);

答案 3 :(得分:0)

以下是我的全部代码:

    public void SendMail()
{
    MailMessage msg = new MailMessage();
    msg.From = new MailAddress("contact@yourwebsite.com");
    string s = txtEmail.Text;
    msg.To.Add(txtEmail.Text);
    msg.Body = "<html><body><img src='~/images/back.png'/><br></body></html>";
    msg.IsBodyHtml = true;
    msg.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Attachment at = new Attachment(Server.MapPath("~/Main/images/English.pdf"));
    //Dim at1 As New Attachment(Server.MapPath("~/Main/images/English.pdf"))
    msg.Attachments.Add(at);
    //msg.Attachments.Add(at1)
    msg.Priority = MailPriority.High;
    msg.Subject = "Special Gift";
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;
    smtp.Credentials = new System.Net.NetworkCredential("yourgmail@gmail.com", "gmailpassword");
    smtp.Send(msg);
}