Saya menggunakan kode berikut dari jawaban ini Mengirim email dalam .NET melalui Gmail . Masalah yang saya alami adalah menambahkan lampiran ke email. Bagaimana saya menambahkan lampiran menggunakan kode di bawah ini?
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);
}
Terima kasih sebelumnya.
Objek message
yang dibuat dari pemanggilan metode new MailMessage
Anda memiliki properti .Attachments
.
Sebagai contoh:
message.Attachments.Add(new Attachment(PathToAttachment));
Menggunakan kelas lampiran seperti yang diusulkan di 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);
Perbaiki kode Anda seperti ini
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
semoga ini bisa membantu Anda.
ricky
Jawaban satu baris:
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));