1

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

Amy
  • 503
  • 4
  • 9
  • 20
  • Okay cool, so FirstOrDefault is when you only want the first element in a sequence. What would I put if I want all the elements? I'm very new to MVC and C# – Amy Oct 04 '11 at 22:18
  • http://msdn.microsoft.com/en-us/vcsharp/aa336746 – Wonko the Sane Oct 05 '11 at 12:30

1 Answers1

0

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.)
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135