2011-02-17 92 views
26

我使用以下代碼從此答案Sending email in .NET through Gmail。我遇到的麻煩是給電子郵件添加附件。我將如何使用下面的代碼添加附件?使用C#向電子郵件添加附件

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

在此先感謝。

回答

61

new MailMessage方法調用中創建的message對象有一個屬性.Attachments

例如:

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

這,謝謝大家。 如此簡單而有效的+1 – Bauer 2015-08-21 19:13:11

15

使用附件類如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); 
0

一個行回答:

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