0

Mail Sender Task should be sending mail Asynchronously, however, it does not seem to be waiting when sending mail to multiple recipients. Some mails are not being sent.

View used to select multiple recipients from a TagBox and then send e-mail notifications:

<p class="alert-danger">@Model</p>
<form method="post">
<div id="form-demo">
    <div class="widget-container">
        <div class="dx-field">
            <div class="dx-field-value">
                @(Html.DevExtreme().TagBox()
                    .Label("Email To:").LabelMode(EditorLabelMode.Floating)
                    .DataSource(d => d.WebApi().Controller("LongLeadNotifications").LoadAction("LongLeadsMessagingLookup").Key("Value"))
                    .Width(650)
                    .ValueExpr("Value")
                    .DisplayExpr("Text")
                    .ShowSelectionControls(true)
                    .ApplyValueMode(EditorApplyValueMode.UseButtons)
                    .OnValueChanged("email_valueChanged")
                )
            </div>
        </div>

        <div class="buttongroups-container">
            @(Html.DevExtreme().ButtonGroup()
                .KeyExpr("alignment")
                .StylingMode(ButtonStylingMode.Text)
                .Items(items => {
                    items.Add().Icon("email").Hint("Send Email").Text("Send Notifications");
                })
                .OnItemClick(@<text>
                                function showInfo(data) {
                                    eMailToAddress.forEach(element => {
                                        console.log(element.replace("\"","").replace("[","").replace("]","").replace("\"",""));
                                        
                                        var value = element.replace("\"","").replace("[","").replace("]","").replace("\"","");
                                        $.ajax({
                                                type: 'POST',
                                                url: '@Url.Action("GetNotifications", "LongLeadNotifications")',
                                                data:{ strEmail: value},
                                                dataType: 'json',
                                                success: () => {
                                                    console.log(value + " is sent");
                                                },
                                                error: (error) => {
                                                    console.log(JSON.stringify(error));
                                                }
                                            });
                                    });

                                    const message = `Email is sent to ` + eMailToAddress;
                                    DevExpress.ui.notify({
                                        message: message,
                                        position: {
                                            my: "center top",
                                            at: "center top"
                                        }
                                    }, "success", 3000);
                                }
                            </text>))
         </div>
               
        @Html.AntiForgeryToken()
        </div>
    </div>
</form>

Controller:

public async Task<IActionResult> GetNotificationsAsync(string strEMail)
        {
        // …

            if (strMessageBody != "")
            {
                strMessageBody = strFirstName + "," + "<br>" + "<br>" + strIntro + strMessageBody + strClosing;

                await GmailSender.SendGmailAsync("myemail@cps.edu", strSubject, strMessageBody, true, null);
                return NoContent();

            }

            return NoContent();
        }

EMailSender.cs:

using System;
using System.Threading.Tasks;
using System.Net.Mail;


namespace CPSPMOReporting
{
    public class GmailSender
    {
        public static async Task<string> SendGmailAsync(string ToEmails, string Subject, string Body, bool IsHtml, string AttachmentPath)
        {
            try
            {
                string GmailAccount = "myemail@cps.edu"; 
                string GmailPassword = "mypassword"; 

                MailMessage mail = new MailMessage(GmailAccount, ToEmails);
                mail.Subject = Subject;
                mail.IsBodyHtml = IsHtml;
                mail.Body = Body;
                if (!string.IsNullOrWhiteSpace(AttachmentPath))
                {
                    Attachment attachment = new Attachment(AttachmentPath);
                    mail.Attachments.Add(attachment);
                    mail.Priority = MailPriority.High; // optional
                }

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(GmailAccount, GmailPassword);

                smtp.SendCompleted += (s, e) => { smtp.Dispose(); };
                await smtp.SendMailAsync(mail);
                    
                return ""; // return nothing when it is successful
            }
            catch (Exception ex)
            {
                return "An error occured while sending your message. " + ex.Message;
            }
        }
    }
}

I tried selecting all of the recipients from the TagBox and clicked on the "Send Notifications" button. I expected all of the recipients to receive an email notification. However, random recipients are skipped each time I try sending. If I select them individually, the notification will be sent.

I would greatly appreciate help with this issue.

Thanks!

Chris
  • 13
  • 3
  • javascript is async by default, so your each function will call the controller async. (Those are separate requests, so await with the .cs file would have no effect...) Not sure that has anything to do with the random skips though... check for bounce-backs. (and it might help to assign something to your returned value(s)... var retval = await yourmethod()... and check those.) – pcalkins Nov 21 '22 at 22:47
  • @pcalkins Thank you for your reply. I will try your suggestions. – Chris Nov 22 '22 at 20:33

1 Answers1

0

It seems that Google will block multiple rapid eMails from your personal account to avoid spam:

https://support.google.com/mail/answer/81126

Looks like a sleep timer may help.

Gmail SMTP error - Temporary block?

Chris
  • 13
  • 3