SendGrid SMTP API:嵌入图像:错误请求 [英] SendGrid SMTP API : Embed Image : Bad Request

查看:32
本文介绍了SendGrid SMTP API:嵌入图像:错误请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sendgrid SMTP API https://github.com/sendgrid/sendgrid-csharp 发送电子邮件,但我不知道如何嵌入图像.我可以使用 .Net 本机邮件 API 做到这一点,没有问题.我只是收到一个错误的请求.这是我抛出的代码

I am using the sendgrid SMTP API https://github.com/sendgrid/sendgrid-csharp to send emails but I cannot figure out how to embed an image. I can do it using .Net native mail api without issues. I am simply getting a Bad Request. Here is my code that is throwing

private static void Main(string[] args)
    {
        try {
           //// Create the email object first, then add the properties.
            var myMessage = new SendGridMessage();

            contact_list = new List<MailAddress>();
            contact_list.Add(new MailAddress("email@gmail.com"));
            myMessage.To = contact_list.ToArray();
            myMessage.From = new MailAddress("clientservice@stpis.com");
            myMessage.Subject = "Subject";

            string html = "<div><img src=cid:Logo /></div>";

            myMessage.Html = html;
            myMessage.EmbedImage(@"C:\logo.png", "Logo");

            SendMessage(myMessage);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }

    private static void SendMessage(SendGridMessage message)
    {
        // Create credentials, specifying your user name and password.
        var credentials = new NetworkCredential("username", "pwdpwdpwd");

        // Create a Web transport for sending email.
        var transportWeb = new Web(credentials);

        // Send the email.
        try
        {
            transportWeb.Deliver(message);
            Console.WriteLine("Sent!");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

推荐答案

我想出了如何让它发挥作用.这是使用的代码:

I figured out how to get this working. Here is the code used:

var myMessage = new SendGridMessage();

contact_list = new List<MailAddress>();
contact_list.Add(new MailAddress("my email address"));

myMessage.To = contact_list.ToArray();
myMessage.From = new MailAddress("clientservice@stpis.com", "STP Client Service");
myMessage.Subject = "STP Report Package: " + package_report_name;
string img = @"C:\\logo.png";
ContentType ctype = new ContentType("image/png");
var attachment = new Attachment(img, ctype);
var linkedResource = new LinkedResource(img, ctype);
myMessage.AddAttachment(attachment.ContentStream, attachment.Name);
myMessage.EmbedImage(attachment.Name, linkedResource.ContentId);

string html = "<img src=cid:"+linkedResource.ContentId+" />";
myMessage.Html = html;

这篇关于SendGrid SMTP API:嵌入图像:错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆