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

问题描述 投票:0回答:5

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

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# .net email gmail smtpclient
5个回答
130
投票

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

例如:

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

19
投票

按照 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);

9
投票

像这样更正你的代码

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

希望这对你有帮助。

瑞奇


1
投票

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

mail.Attachments.Add(new Attachment(file));
mail.Body = "body";

0
投票

一行答案:

mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));
© www.soinside.com 2019 - 2024. All rights reserved.