jeudi 28 octobre 2021

Failure to trigger message when e-mails are sent asynchronously

I have a method that sends e-mails (using FluentEmail), and I want to trigger a message when they're sent. They are sent asynchronously. This is my method:

using System.Net;
using System.Net.Mail;
using FluentEmail.Core;
using FluentEmail.Smtp;

public void SendEmail() {

    try {

        var sender = new SmtpSender(() => new SmtpClient(host: "smtp.office365.com") {
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("my@email.com", "myPassword"),
            Port = 587
        });

        Email.DefaultSender = sender;

        var newEmail = Email
            .From("my@email.com")
            .To("their@email.com")
            .Subject("a thousand blessings upon you")
            .Body("receive these blessings");

        foreach (var company in groupedByCompany) {

            string o = company.Select(x => x.PropertyName).FirstOrDefault().ToString();
            string n = company.Select(x => x.ProperyNameTwo).FirstOrDefault().ToString();
            newEmail.AttachFromFilename($@"C:\filepath\{o + n}", "application/pdf", "this is the preview text");

        var result = newEmail.SendAsync();

        if (result.IsCompleted == true) { //this is System.Threading.Tasks.Task<FluentEmail.Core.Models.SendResponse> result

            Console.WriteLine("E-mail sent!");

        } else {

            Console.WriteLine("Could not send e-mail.");
        }

    } catch (Exception ex) {

        // handle exception
    }
}

But the e-mail is sent without any messages in Output. I see that IsCompleted will be true if one of three conditions are met:

TaskStatus.RanToCompletion

TaskStatus.Faulted

TaskStatus.Canceled

What could I use instead of IsCompleted / what am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire