Adding an attachment to email using C#

.net, c#, email, gmail, smtpclient

Solution

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

For example:

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

Problem

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("from@gmail.com", "From Name"); var toAddress = new MailAddress("to@example.com", "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); } ```

Original source

Related problems