Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an attachment to email using C#

Tags:

c#

.net

email

gmail

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

For example:

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

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

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


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