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

C# 使用C向电子邮件添加附件#,c#,.net,email,gmail,C#,.net,Email,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

我使用的代码如下。我遇到的麻烦是在电子邮件中添加附件。如何使用下面的代码添加附件

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

提前感谢。

使用附件类,如:


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

例如:

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

像这样更正代码

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);

希望这对你有帮助

瑞奇

一句话的回答:

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

提示:若在之后添加附件,邮件正文将被附件文件路径覆盖,所以请先附加,然后再添加正文

mail.Attachments.Add(新附件(文件))


mail.Body=“Body”

MSDN上的“官方文档”非常粗略地描述了附件实际附加的内容。就像你的例子没有解释什么是“文件”,或者如果它有效的话会附加什么。这个答案是不完整的。如果附件不在文件系统中,但您有一个字节流,该怎么办?@barduro OP没有询问这个特殊情况。为此,请参见
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));