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

rro*_*oss 47 .net c# email gmail

我正在使用此答案中的以下代码通过Gmail在.NET中发送电子邮件.我遇到的麻烦是在电子邮件中添加附件.如何使用下面的代码添加附件?

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);
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

JYe*_*ton 89

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

例如:

message.Attachments.Add(new Attachment(PathToAttachment));
Run Code Online (Sandbox Code Playgroud)

  • @barduro OP 没有询问这个特殊情况。为此,请参阅/sf/answers/180879401/ (3认同)

Mat*_*ten 17

使用MSDN中建议的Attachment类:

// 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);
Run Code Online (Sandbox Code Playgroud)

  • MSDN 上的“官方文档”对于附件实际附加的内容非常粗略。就像您的示例没有解释“文件”是什么或者如果有效的话将附加什么内容。 (2认同)

小智 8

像这样纠正你的代码

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
Run Code Online (Sandbox Code Playgroud)

http://csharp.net-informations.com/communications/csharp-email-attachment.htm

希望这会帮助你.

瑞奇