【问题标题】:Why can't attach attachments by mail with sendgrid?为什么用 sendgrid 不能通过邮件附加附件?
【发布时间】:2019-01-18 22:23:31
【问题描述】:

当我尝试发送带有位于谷歌驱动器或存储库路径中的附件的电子邮件时,它只发送电子邮件但不发送文件。

我尝试以字节为单位下载文件,然后将其作为附件发送

使用的代码如下

List<Attachment> files = new List<Attachment>
{  
   new Attachment()
   {
      Content = "BwdW",
      Type = "image/png",
      Filename = Server.MapPath("~/Content/IMG/EmailHeader.png"),
      Disposition = "inline",
      ContentId = "EmailHeader"
   } 
};

这是方法:

 public Boolean EnvioCorreo_Copias_Archivos(string cuerpo, string asunto, string correoEmisor, List<EmailAddress> correoReceptor,
                                               List<Attachment> Archivos)
    {
        try
        {
            var clientSendGrid = new SendGridClient("Key_Sendgrid");
            var from = new EmailAddress(correoEmisor, "Alias"); 
            List<EmailAddress> tos = correoReceptor;

            var body = cuerpo; 
            var subject = asunto;
            var plainTextContent = "";
            var htmlContent = body;
            var showAllRecipients = true;

            var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent, showAllRecipients); 
            msg.AddAttachments(Archivos); 
            clientSendGrid.SendEmailAsync(msg).Wait(); 
            return true;
        }
        catch (Exception)
        {

            return false;
        }
    }

【问题讨论】:

  • 您将文件附加到电子邮件并发送的部分在哪里?
  • 嗨,AseraH,我已经把发送邮件的完整方法放好了。
  • 您创建了附件,但从未以编程方式将其添加到电子邮件中。您缺少将files 添加到电子邮件的行。
  • @Renan,List Archivos,是文件进来的参数
  • @Renan 这只是一种可重复使用的方法

标签: c# email attachment sendgrid


【解决方案1】:

我个人将其用于单个电子邮件附件:

var Message = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var bytes = System.IO.File.ReadAllBytes(AttachmentPath);
var File = Convert.ToBase64String(bytes);
Message.AddAttachment(FileName, File);
APIResponse = await client.SendEmailAsync(Message).ConfigureAwait(false);

【讨论】:

  • 这是以正确方式读取文件的最佳解决方案。有时您还会发现:byte[] byteData = Encoding.ASCII.GetBytes(File.ReadAllText(filePath)); 但不会以正确的方式读取每个文件...
【解决方案2】:

我刚刚确认这适用于 SendGrid,附件工作正常:

var msg = new MailMessage(fromAddress, toAddress)
{
  Subject = "attachment test", 
  IsBodyHtml = true, 
  Body = "this is the body"
};

var attachment = new Attachment(attachmentPath);
msg.Attachments.Add(attachment);

using (var client = new SmtpClient("smtp.sendgrid.net"))
{
  client.UseDefaultCredentials = false;
  client.EnableSsl = true;
  client.Port = 587;
  client.Credentials = new NetworkCredential("key","password");

  await client.SendMailAsync(msg);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多