Send newsletter

1

I'm trying to send a newsletter to all users who have the newsletter enabled and I can not.

My normal send email code is:

try
{
  SmtpClient smtp = new SmtpClient();
  smtp.UseDefaultCredentials = false;

  smtp.Host = "smtp.gmail.com";
  smtp.Port = 587;
  smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "msg");
  smtp.EnableSsl = true;

  MailMessage msg = new MailMessage();
  msg.Subject = "msg | Newsletter | " + txtAssunto.Text + " - msg";
  msg.Body = "Msg";
  string toAddress = ????
  msg.To.Add(toAddress);

  string fromAddress = "\"msg";
  msg.From = new MailAddress(fromAddress);
  msg.IsBodyHtml = true;
  smtp.Send(msg);

} catch {

}

How can I get all the mails of which have newsletter active, ie SELECT EMAIL FROM UTILIZADORES WHERE NEWSLETTER = 'TRUE' .

How can I do this, so that msg.To.Add(toAddress); only sends mails to users with newsletter active?     

asked by anonymous 07.07.2015 / 04:18

1 answer

1

A simple way to do this would be to perform a query on the database with this query and use the returns the list / array returned to populate addRecipient. In the example below I'm using jdbc and postgres, but you can use any database.

try {
    String url = "jdbc:postgresql://host:porta/database";
    Connection conn = DriverManager.getConnection(url,"usuario","senha");
    Statement stmt = conn.createStatement();
    ResultSet rs;

    rs = stmt.executeQuery("SELECT EMAIL FROM UTILIZADORES WHERE NEWSLETTER = \'TRUE\'");
    List<String> enderecos = new LinkedList<String>();
    while ( rs.next() ) {
        enderecos.add(rs.getString("EMAIL"));
    }
    conn.close();
} catch (Exception e) {
    System.err.println(e.getMessage());
}

and put the return in an array or a list (the preference is yours). And in your code, you can use the .addRecipient method of your Message object. For example:

for (String email : enderecos){
    message.addRecipient(Message.Recipient-type.CC, InternetAddress.parse(email));
}
    
07.07.2015 / 10:36