2011-02-17 26 views
26

Bu yanıtı aşağıdaki koddan kullanıyorum Sending email in .NET through Gmail. Yaşadığım sıkıntı e-postaya bir ek eklemek. Aşağıdaki kodu kullanarak nasıl ek ekleyebilirim?C# kullanarak e-posta eki ekleme #

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

Şimdiden teşekkürler. MSDN önerildiği gibi

cevap

61

sizin new MailMessage yöntem çağrısından oluşturulan message nesne bir özelliğe .Attachments sahiptir. Örneğin

:

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

Bu, teşekkür ederim. Çok basit ve etkili +1 – Bauer

15

Eklenti sınıfını kullanarak:

// 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

tek satırlık bir cevap:

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