【问题标题】:Adding an attachment to email using C#使用 C# 向电子邮件添加附件
【发布时间】:2023-03-21 19:34:01
【问题描述】:

我正在使用来自此答案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);
}

提前致谢。

【问题讨论】:

    标签: c# .net email gmail


    【解决方案1】:

    提示:如果后面添加附件,邮件正文将被附件文件路径覆盖,因此请先附加,然后再添加正文

    mail.Attachments.Add(new Attachment(file));

    mail.Body = "正文";

    【讨论】:

      【解决方案2】:

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

      例如:

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

      【讨论】:

      • 这个答案不完整。如果附件不在文件系统中,但你有一个字节流怎么办?
      • @barduro OP 没有询问那个特殊情况。为此,请参阅stackoverflow.com/a/2583991/161052
      【解决方案3】:

      单行答案:

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

      【讨论】:

        【解决方案4】:

        像这样更正你的代码

        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

        希望这会对你有所帮助。

        里奇

        【讨论】:

          【解决方案5】:

          使用MSDN 中建议的附件类:

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

          【讨论】:

          • MSDN 上的“官方文档”对附件实际附加的内容非常粗略。就像您的示例没有解释什么是“文件”或者如果它有效将附加什么。
          猜你喜欢
          • 2011-02-03
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-05
          • 2020-03-06
          • 2020-11-27
          • 2015-03-06
          相关资源
          最近更新 更多