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

wwtsj6pe  于 2022-12-27  发布在  .NET
关注(0)|答案(5)|浏览(160)

我正在使用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);
}
dly7yett

dly7yett1#

通过new MailMessage方法调用创建的message对象具有属性.Attachments
例如:

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

vshtjzan2#

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

e4yzc0pl3#

像这样更正代码

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
希望这对你有帮助。
里基

htzpubme

htzpubme4#

提示:如果在之后添加附件,则附件文件路径会覆盖邮件正文,因此请先添加附件,后添加正文
邮件.附件.添加(新建附件(文件));
邮件。正文=“body”;

mnowg1ta

mnowg1ta5#

一行回答:

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

相关问题