Tôi đang sử dụng đoạn mã sau từ câu trả lời này Gửi email bằng .NET thông qua Gmail . Vấn đề tôi gặp phải là thêm một tệp đính kèm vào email. Làm cách nào để thêm tệp đính kèm bằng mã bên dưới?
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);
}
Cảm ơn trước.
Đối tượng message
được tạo từ lệnh gọi phương thức new MailMessage
của bạn có thuộc tính .Attachments
.
Ví dụ:
message.Attachments.Add(new Attachment(PathToAttachment));
Sử dụng lớp Đính kèm như được đề xuất trong 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);
Sửa mã của bạn như thế này
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
http://csharp.net-informations.com/c truyền thông/csharp-email-attachment.htmlm
hy vọng điều này sẽ giúp bạn.
ricky
Câu trả lời một dòng:
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));