Подтвердить что ты не робот

Добавление вложения в электронную почту с использованием С#

Я использую следующий код из этого ответа Отправка электронной почты в .NET через Gmail. У меня возникла проблема с добавлением вложения в электронную почту. Как добавить вложение с помощью кода ниже?

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

Спасибо заранее.

4b9b3361

Ответ 1

Объект message, созданный из вашего вызова метода new MailMessage, имеет свойство .Attachements.

Например:

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

Ответ 2

Использование класса Attachment, предложенного в 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);

Ответ 4

Ответ на один ответ:

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