Send newsletter

Asked

Viewed 54 times

1

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

My code to send one email normal 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 go to search all the database mails whose they have newsletter active, that is to say SELECT EMAIL FROM UTILIZADORES WHERE NEWSLETTER = 'TRUE'.

How can I do that, so that the msg.To.Add(toAddress); just send mails for the users with newsletter active?

1 answer

1

One simple way to do this would be to perform a query in the database with this query and use the return list/array to fill in addRecipient. In the example below I am using jdbc and postgres, but you can use any bank.

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));
}
  • Could you exemplify it in a more complex way? I have tried it in several ways but without success.

  • In which part are you having difficulties?

  • In the selection of the emails of the users who have the newsletter active. I have tried several ways within Try and could not. I tried to put sql command in string to address and it also didn’t work like this.

  • I updated the answer, now see if the answer is clearer.

  • Have some way to do via stored Procedure?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.