C# 将SMTP Sendgrid转换为Sendgrid API
目前正在将旧的SMTP Sendgrid替换为API Sendgrid,我注意到它们的代码中存在一些差异。但我认为,既然它们都是Sendgrid,那么它就可以工作了。我所做的是添加这个C# 将SMTP Sendgrid转换为Sendgrid API,c#,asp.net,sendgrid,C#,Asp.net,Sendgrid,目前正在将旧的SMTP Sendgrid替换为API Sendgrid,我注意到它们的代码中存在一些差异。但我认为,既然它们都是Sendgrid,那么它就可以工作了。我所做的是添加这个SendGridClient.SendEmailAsync(Message)最后。但是它说 无法从system.net.mail.mailmessage转换为sendgrid.helpers.mail.sendgridmessage 这是转换它的正确方法吗 下面是代码 try {
SendGridClient.SendEmailAsync(Message)代码>最后。但是它说
无法从system.net.mail.mailmessage转换为sendgrid.helpers.mail.sendgridmessage
这是转换它的正确方法吗
下面是代码
try
{
string SendGridKey = ConfigurationManager.AppSettings["SendGridKey"];
var SendGridClient = new SendGridClient(SendGridKey);
using (MailMessage MessageContent = new MailMessage())
{
MessageContent.From = new MailAddress(From);
MessageContent.To.Add(new MailAddress(To));
MessageContent.Subject = Subject;
MessageContent.Body = (TextBody);
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView Alternate = AlternateView.CreateAlternateViewFromString(HtmlBody, mimeType);
Message.AlternateViews.Add(Alternate);
if (AttachedFileName == true)
{
Attachment AttachedFile = new Attachment(HttpRuntime.AppDomainAppPath + "Path\\" + AttachedFileName);
MessageContent.Attachments.Add(AttachedFile);
}
//using (SmtpClient Client = new SmtpClient())
//{
// Client.EnableSsl = true;
// Client.Send(MessageContent);
//}
SendGridClient.SendEmailAsync(Message);
}
return;
}
要使用SendGrid API发送邮件,需要创建com.SendGrid.Request对象。添加java代码:
import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.SendGrid;
Email from = new Email("<FROM_EMAIL>");
String subject = "<SUBJECCT>";
Email to = new Email("<TO_EMAIL>");
Content content = new Content("text/plain", message);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(SendGridKey);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
log.info("Main sent successfully");
} catch (IOException ex) {
log.info("Error while sending mail: {}", ex.toString());
}
导入com.sendgrid.Content;
导入com.sendgrid.Email;
导入com.sendgrid.Mail;
导入com.sendgrid.Method;
导入com.sendgrid.Request;
导入com.sendgrid.sendgrid;
电子邮件发件人=新电子邮件(“”);
字符串主语=”;
电子邮件收件人=新电子邮件(“”);
内容=新内容(“文本/普通”,消息);
邮件=新邮件(发件人、主题、收件人、内容);
SendGrid sg=新的SendGrid(SendGridKey);
请求=新请求();
试一试{
request.setMethod(Method.POST);
request.setEndpoint(“邮件/发送”);
request.setBody(mail.build());
sg.api(请求);
log.info(“主发送成功”);
}捕获(IOEX异常){
info(“发送邮件时出错:{}”,例如toString());
}
您需要创建sendgrid.helpers.mail.sendgridmessage
类的对象,设置其属性,然后将其传递给SendGridClient.SendEmailAsyc
方法。我已经这样做了。我成功地发送了一封电子邮件。但我希望只更改旧smtp中的几行代码,而不是创建一个全新的smtp。github上为此打开了一个问题。。。也许你可以编写自己的实现并帮助社区。。