Sending an email with attachment using SendGrid

半腔热情 提交于 2019-11-30 05:58:02

问题


 var myMessage = new SendGridMessage();
            myMessage.From = new MailAddress("info@email.com");
            myMessage.AddTo("Cristian <myemail@email.com>");
            myMessage.Subject = user.CompanyName + "has selected you!";
            myMessage.Html = "<p>Hello World!</p>";
            myMessage.Text = "Hello World plain text!";

           // myMessage.AddAttachment("C:\test\test.txt");



            var apiKey = "";
            var transportWeb = new Web(apiKey);
            transportWeb.DeliverAsync(myMessage);

Basically I can make the email work, and the moment I attempt to add an attachment it doesn't send it. I tried different paths and different ways of writing the path, I am not sure what is going wrong, every single tutorial I have found shows it should work like this.


回答1:


I got it to work, turns out I just needed a virtual path:

myMessage.AddAttachment(Server.MapPath(@"~\img\logo.png"));



回答2:


\ it is a escape character

//Initialize with a regular string literal.

myMessage.AddAttachment(@"C:\test\test.txt");

else // Initialize with a verbatim string literal.

myMessage.AddAttachment("C:\\test\\test.txt");



回答3:


attach blob reference doc using sendgrid

mail.AddAttachment(AzureUploadFileClsName.MailAttachmentFromBlob("DocName20190329141433.pdf"));

common method you can create as below one.

public static Attachment MailAttachmentFromBlob(string docpath)
    {
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(storageContainer);
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(docpath);
        blockBlob.FetchAttributes();
        long fileByteLength = blockBlob.Properties.Length;
        byte[] fileContent = new byte[fileByteLength];
        for (int i = 0; i < fileByteLength; i++)
        {
            fileContent[i] = 0x20;
        }
        blockBlob.DownloadToByteArray(fileContent, 0);

        return new Attachment{ Filename = "Attachmentname",
            Content = Convert.ToBase64String(fileContent),
            Type = "application/pdf",
            ContentId = "ContentId" };

    }


来源:https://stackoverflow.com/questions/37945281/sending-an-email-with-attachment-using-sendgrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!