2

I want to send a pdf file with a mail in C#. I know how I can send a mail but I don't know how I can send a mail with pdf file :(

For example I have a pdf file in the folder C:\test.pdf

Here is my code:

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;
    }
}
Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
Tarasov
  • 3,625
  • 19
  • 68
  • 128

4 Answers4

4

You can do like this :

var filename = @"c:\test.pdf";
m.Attachments.Add(new Attachment(filename));
Jonas W
  • 3,200
  • 1
  • 31
  • 44
2

You need to add it as attachment.

Check the MSDN documentation regarding this - http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments.aspx

dutzu
  • 3,883
  • 13
  • 19
1
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("filename");
m.Attachments.Add(attachment);
0

Here is the entire code of mine:

    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);
}
coder
  • 13,002
  • 31
  • 112
  • 214