Adding an attachment to email using C#

C#.NetEmailGmail

C# Problem Overview


I'm using the following code from this answer https://stackoverflow.com/questions/32260/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.

C# Solutions


Solution 1 - C#

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

For example:

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

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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";

Solution 5 - C#

A one line answer:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrrossView Question on Stackoverflow
Solution 1 - C#JYeltonView Answer on Stackoverflow
Solution 2 - C#MattenView Answer on Stackoverflow
Solution 3 - C#rickymannarView Answer on Stackoverflow
Solution 4 - C#Hasan NazeerView Answer on Stackoverflow
Solution 5 - C#Rob SalmonView Answer on Stackoverflow