Adding an attachment to email using C#

rross picture rross · Feb 17, 2011 · Viewed 83.7k times · Source

I'm using the following code from this answer Sending email in .NET through Gmail. The trouble I'm having is adding an attachment to the email. How would I add an attachment using the code below?

using System.Net.Mail;

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body
    })
{
    smtp.Send(message);
}

Thanks in advance.

Answer

JYelton picture JYelton · Feb 17, 2011

The message object created from your new MailMessage method call has a property .Attachments.

For example:

message.Attachments.Add(new Attachment(PathToAttachment));