C# 使用SendGrid发送电子邮件
我正在尝试从sendgrid发送电子邮件,如下所示-C# 使用SendGrid发送电子邮件,c#,asp.net,async-await,sendgrid,C#,Asp.net,Async Await,Sendgrid,我正在尝试从sendgrid发送电子邮件,如下所示- public static async Task<int> SendEmail(string fromEmail, string toEmail, string emailMessage, string subject) { try { // Create the email object first, then add the properties. var myMessage =
public static async Task<int> SendEmail(string fromEmail, string toEmail, string emailMessage, string subject)
{
try
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
// Add the message properties.
myMessage.AddTo(toEmail);
myMessage.From = new MailAddress(fromEmail);
myMessage.Subject = subject;
myMessage.Html = emailMessage;
var username = ConfigurationManager.AppSettings["NetworkUserId"];
var pswd = ConfigurationManager.AppSettings["NetworkUserPwd"];
var domain = ConfigurationManager.AppSettings["HostName"];
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(username, pswd, domain);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
if (transportWeb != null)
await transportWeb.DeliverAsync(myMessage);
else
{
await Task.FromResult(0);
}
}
catch (System.Exception ex)
{
//throw ex;
}
return 1;
}
公共静态异步任务SendEmail(字符串fromEmail、字符串toEmail、字符串emailMessage、字符串subject)
{
尝试
{
//首先创建电子邮件对象,然后添加属性。
var myMessage=new SendGridMessage();
//添加消息属性。
myMessage.AddTo(toEmail);
myMessage.From=新邮件地址(fromEmail);
myMessage.Subject=Subject;
Html=emailMessage;
var username=ConfigurationManager.AppSettings[“NetworkUserId”];
var pswd=ConfigurationManager.AppSettings[“NetworkUserPwd”];
var domain=ConfigurationManager.AppSettings[“主机名”];
//创建凭据,指定用户名和密码。
var凭证=新的网络凭证(用户名、pswd、域);
//创建用于发送电子邮件的Web传输。
var transportWeb=新站点(凭证);
如果(transportWeb!=null)
等待transportWeb.DeliverAsync(myMessage);
其他的
{
等待任务。从结果(0);
}
}
catch(System.Exception-ex)
{
//掷骰子;
}
返回1;
}
在这里,我使用async和Wait,我成功地获得了邮件,但我希望返回值为1。我认为我的调试器将挂起等待。您不需要等待0的结果,您的代码应该是:
public static async Task<int> SendEmail(string fromEmail, string toEmail, string emailMessage, string subject) {
try {
// Same as your example
if (transportWeb != null)
await transportWeb.DeliverAsync("");
else {
return 0;
}
}
catch (System.Exception ex) {
//throw ex;
}
return 1;
}
公共静态异步任务SendEmail(字符串fromEmail、字符串toEmail、字符串emailMessage、字符串subject){
试一试{
//和你的例子一样
如果(transportWeb!=null)
等待transportWeb.DeliverAsync(“”);
否则{
返回0;
}
}
catch(System.Exception-ex){
//掷骰子;
}
返回1;
}
如果使用正确,则此代码不应返回1
。如果你没有得到这个值,那么我猜你会遇到某种死锁的情况。没有看到调用代码,尽管这只是一个猜测。如果您能更清楚地了解这里到底发生了什么,这会有所帮助。实际上,我在“await transportWeb.DeliverAsync(myMessage);”中丢失了我的调试器,并且在调用此方法的地方找不到任何响应。我想等待在这里不起作用。我猜你有某种僵局的情况。虽然这只是一个猜测,但没有看到调用代码。谢谢,但实际上我在“wait-transportWeb.DeliverAsync(“”;”)之后丢失了调试器。