62

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);
}

5 Answers 5

123

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

For example:

message.Attachments.Add(new Attachment(PathToAttachment));
2
  • This answers is incomplete. What if the attachments is not sitting in the file system, but you have a stream of byte?
    – barduro
    Sep 26, 2019 at 15:42
  • 3
    @barduro The OP did not ask about that particular case. For that, see stackoverflow.com/a/2583991/161052
    – JYelton
    Sep 26, 2019 at 16:45
19

Using the Attachment class as proposed in the MSDN:

// Create  the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
1
  • 2
    The "official documentation" on MSDN is pretty sketchy about what an Attachment actually attaches. Just like your example doesn't explain what "file" is or what will be attached if it works.
    – Suncat2000
    Aug 15, 2019 at 19:05
9

Correct your code like this

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);

http://csharp.net-informations.com/communications/csharp-email-attachment.htm

hope this will help you.

ricky

1

Hint: mail body is overwritten by attachment file path if attachment is added after, so attach first and add body later

mail.Attachments.Add(new Attachment(file));

mail.Body = "body";

0

A one line answer:

mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.