使用 C# 添加附件到电子邮件
我使用此答案中的以下代码通过 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);
}
I'm using the following code from this answer Sending email in .NET through Gmail. The trouble I'm having is adding an attachment to the email. How would I add an attachment using the code below?
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通过
new MailMessage
方法调用创建的message
对象具有属性.Attachments
。例如:
The
message
object created from yournew MailMessage
method call has a property.Attachments
.For example:
使用 MSDN:
Using the Attachment class as proposed in the MSDN:
像这样更正您的代码
http://csharp.net-informations.com/ communications/csharp-email-attachment.htm
希望这会对您有所帮助。
瑞奇
Correct your code like this
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
hope this will help you.
ricky
提示:如果之后添加附件,邮件正文会被附件文件路径覆盖,因此先附加后添加正文
Hint: mail body is overwritten by attachment file path if attachment is added after, so attach first and add body later
一行答案:
A one line answer: