使用SendGrid发送电子邮件

时间:2018-05-30 06:05:55

标签: 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 = 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;
}

我在这里使用async和await,我收到了成功邮件,但我希望返回值为1.我认为我的调试器会等待。

1 个答案:

答案 0 :(得分:-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;
    }