sending multiple emails with mvcmailer

2019-05-09 13:38发布

Im looking to use MVCMailer to send emails using asp.net mvc 3 with razor. Also mentioned by ScottHa

It looks fairly straight forward, however i'm confused as to how I would send batch emails eg like a newsletter to a list of users.

do i create a loop around this?

public virtual MailMessage Welcome()
{
    var mailMessage = new MailMessage{Subject = "Welcome to MvcMailer"};

    mailMessage.To.Add("sohan39@example.com");
    ViewBag.Name = "Sohan";
    PopulateBody(mailMessage, viewName: "Welcome");

    return mailMessage;
}

can someone explain? thanks

2条回答
老娘就宠你
2楼-- · 2019-05-09 13:46

Unfortunately because each email message is personalized, I can't see any other way other than looping. So just change your method to something like:

public virtual MailMessage Welcome(string email, string name)
{
    var mailMessage = new MailMessage{Subject = "Welcome to MvcMailer"};

    mailMessage.To.Add(email);
    ViewBag.Name = name;
    PopulateBody(mailMessage, viewName: "Welcome");

    return mailMessage;
}

And then call that method inside your loop and send it at the same time.

Important Note

You should setup your web.config to use a pickup directory rather than a SMTP server. Then get IIS to send the email from the pickup directory.

Reasoning - Because you could potentially be calling SmtpClient.Send(MailMessage mailmessage) any number of times - this could become rather expensive if you have to connect to a SMTP server each time to send the email.

A nice side effect of this is you also get some redundancy if the SMTP server is down or unreachable for any reason.

查看更多
姐就是有狂的资本
3楼-- · 2019-05-09 13:49

If you want different content for each email, you'll need to create individual MailMessage objects using a loop. If you want the same contents, then you can just add multiple recipients:

mailMessage.To.Add("sohan39@example.com");
mailMessage.To.Add("peter23@example.com");
查看更多
登录 后发表回答