Send mail with smtp SendAsync

后端 未结 3 650
滥情空心
滥情空心 2021-01-24 22:58

this is how when I need to send email gives me error. But the mistake that since gives me is this:

An asynchronous operation cannot be started at this tim

3条回答
  •  日久生厌
    2021-01-24 23:39

    Change your method to:

    public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage)
    {
    var message = new MailMessage();
    message.To.Add(toEmailAddress);
    
    message.Subject = emailSubject;
    message.Body = emailMessage;
    
    using (var smtpClient = new SmtpClient())
    {
        await smtpClient.SendMailAsync(message);
    }
    }
    

    And call it like:

    var task = SendEmail(toEmailAddress, emailSubject, emailMessage);
    var result = task.WaitAndUnwrapException();
    

    Have a look here Asynchronously sending Emails in C#? and here How to call asynchronous method from synchronous method in C#?

提交回复
热议问题