Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await MailMessage.SendAsync?

If I do this:

public async Task<SendEmailServiceResponse> ExecuteAsync(SendEmailServiceRequest request)
    {
        ....
        var response = new SendEmailServiceResponse();
        await client.SendAsync(mail, null); // Has await
        response.success = true;
        return response;
    }

Then I get this:

Cannot await 'void'

But if I do this:

public async Task<SendEmailServiceResponse> ExecuteAsync(SendEmailServiceRequest request)
    {
        ....
        var response = new SendEmailServiceResponse();
        client.SendAsync(mail, null); // No Await
        response.success = true;
        return response;
    }

I get this:

The async method lacks 'await' and will run synchronously.

I'm clearly missing something, just not sure what.

like image 534
Casey Crookston Avatar asked May 10 '17 19:05

Casey Crookston


1 Answers

As others have pointed out SendAsync is a bit misleading. It returns a void, not a Task. If you want to await a send mail call you need to use the method

SendMailAsync(MailMessage message)

or

SendMailAsync(string from, string recipients, string subject, string body)

Both of these return a Task and can be awaited

like image 100
maccettura Avatar answered Oct 14 '22 03:10

maccettura