开发者

Send Multiple Emails with MvcMailer

开发者 https://www.devze.com 2023-04-10 11:20 出处:网络
I am developing an MVC 3 project and would like to send invoices out to clients each month by email. How would I send out these multiple emails, and if a loop, how would I code this loop?

I am developing an MVC 3 project and would like to send invoices out to clients each month by email. How would I send out these multiple emails, and if a loop, how would I code this loop?

Here is my InvoiceMailer code:

    public virtual MailMessage InvoiceMailed()
    {
        var invoices = db.Invoice.FirstOrDefault();
        var client = db.Clients.FirstOrDefault();


        var mailMessage = new MailMessage{Subject = "InvoiceMailed"};

        mailMessage.To.Add("amecily@gmail.com");
        mailMessage.Bcc.Add(client.EmailAddress);
        ViewBag.Name = client.FullName;
        ViewBag.Number = invoices.InvoiceNumberID;
        ViewBag.Amount = invoices.InvoiceAmount;
        ViewBag.Month = invoices.InvoiceMonth;
 开发者_高级运维       PopulateBody(mailMessage, viewName: "InvoiceMailed");

        return mailMessage;

    }

And the view for my email:

Hello @ViewBag.Name
<br /><br />
This is your invoice from DFP Productions for the month of @ViewBag.Month
<br /><br />
@ViewBag.Number<br />
@ViewBag.Amount<br />
@ViewBag.Month<br />

The email is currently sending, but obviously only with one set of information and only sends to two of three recipients (is this due to FirstOrDefault and what should I use instead?).

Thanks, Amy


The basic logic would be

  • Get the set of clients to be billed.
  • instantiate an instance of SmtpClient, connecting to your MTA
  • For each client in the set,
    • compute their invoice data
    • construct an instance of MailMessage as appropriate, using the client and the client's invoice data.
    • Post the message via your SmtpClient instance
  • Dispose of the SmtpClient instance (and any other IDisposables that are no longer needed.)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号