使用C#向电子邮件添加附件

时间:2011-02-17 20:52:21

标签: c# .net email gmail

我正在使用此回答Sending email in .NET through Gmail中的以下代码。我遇到的麻烦是在电子邮件中添加附件。如何使用下面的代码添加附件?

using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "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);
}

提前致谢。

5 个答案:

答案 0 :(得分:83)

message方法调用创建的new MailMessage对象具有属性.Attachments

例如:

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

答案 1 :(得分:16)

使用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);

答案 2 :(得分:8)

像这样纠正你的代码

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

希望这会对你有所帮助。

瑞奇

答案 3 :(得分:1)

提示:如果在后面添加附件,邮件正文会被附件文件路径覆盖,所以先附加后添加正文

mail.Attachments.Add(new Attachment(file));

mail.Body = "body";

答案 4 :(得分:0)

一行答案:

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