17

I'm trying to send emails with java from database. After I run my main method for some reason I'm getting this error:

Exception in thread "main" javax.mail.internet.AddressException: Illegal semicolon, not in group in string ``john@gmail.com;eric@gmail.com;carrie@gmail.com;mark@gmail.com;britney@gmail.com'' at position 23
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:929)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:638)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:615)
    at EmailSender.sendEmail(TestSendEmails.java:120)
    at EmailSender.sendEmail(TestSendEmails.java:128)
    at Main.main(Main.java:8)

I'm assuming that my array list is built wrong. Here is my code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestSendEmails {
    private String emailTo;
    private String emailSubject;
    private String emailBody;
    private String emailAttachments;

    public TestSendEmails(){

    }

    public TestSendEmails(String emailTo, String emailSubject, String emailBody, String emailAttachments){
        super();
        this.emailTo = emailTo;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;
        this.emailAttachments = emailAttachments;
    }

    public String getEmailTo(){
        return emailTo;
    }

    public void setEmailTo(String emailTo){
        this.emailTo = emailTo;
    }

    public String getEmailSubject(){
        return emailSubject;
    }

    public void setEmailSubject(String emailSubject){
        this.emailSubject = emailSubject;
    }

    public String getEmailBody(){
        return emailBody;
    }

    public void setEmailBody(String emailBody){
        this.emailBody = emailBody;
    }

    public String getEmailAttachments(){
        return emailAttachments;
    }

    public void setEmailAttachments(String emailAttachments){
        this.emailAttachments = emailAttachments;
    }
}

class TestSendEmailD{
    private Connection con;

    private static final String GET_EMAILS = "Select * From Emails";

    private void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        con = DriverManager.getConnection("jdbc:sqlserver://100.000.000.00\\SQLEXPRESS:3333;databaseName=dEmails;user=sys;password=admin");
    }

    public List<TestSendEmails> getTestSendEmails() throws Exception{
        connect();
        PreparedStatement ps = con.prepareStatement(GET_EMAILS);
        ResultSet rs = ps.executeQuery();
        List<TestSendEmails> result = new ArrayList<TestSendEmails>();
        while(rs.next()){
            result.add(new TestSendEmails(rs.getString("emailTo"), rs.getString("emailSubject"),rs.getString("emailBody"),rs.getString("emailAttachments")));
        }
        disconnect();
        return result;
    }

    private void disconnect() throws SQLException{
        if(con != null){
            con.close();
        }
    }
}

class EmailSender{
    private Session session;

    private void init(){
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "100.000.000.00");
        props.put("mail.smtp.port", "123");

        session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("work@gmail.comg", "1234");
                    }
                  });
    }

    public void sendEmail(TestSendEmails s) throws MessagingException{
        init();
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("work@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo()));
        message.setSubject(s.getEmailSubject());
        message.setText(s.getEmailBody());
        Transport.send(message);
    }

    public void sendEmail(List<TestSendEmails> emails) throws MessagingException{
        for(TestSendEmails TestSendEmails:emails ){
            sendEmail(TestSendEmails);
        }
    }
}

here is my main.java:

public class Main {
    public static void main(String[] args) throws Exception {
        TestSendEmailD dao=new TestSendEmailD();
        List<TestSendEmails> list=dao.getTestSendEmails();
        EmailSender sender=new EmailSender();
        sender.sendEmail(list);
    }
}

Can anyone help with this? Thanks in advance.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193
  • `SendEmails` and `TestSendEmails`? where it is – SatyaTNV Jul 17 '15 at 12:22
  • Please give `emailTo` string.. I guess there is some problem in that string – Ashish Patil Jul 17 '15 at 12:23
  • I edit my question you can see code now. – espresso_coffee Jul 17 '15 at 12:28
  • @moffeltje,I mean the exact value of `emailTo` (`emailTo` should be some database column and there is some value for that column.) And as per exception, there is possibility that senders list is not stored properly. I am assumming this since no further info is present while posting my comment. – Ashish Patil Jul 17 '15 at 12:29
  • 1
    You have to use a comma separated list for `InternetAddress.parse()` to parse it correctly. – user432 Jul 17 '15 at 12:29
  • @AshishPatil The edit made your point correct! – moffeltje Jul 17 '15 at 12:30
  • Can you provide the code for that? – espresso_coffee Jul 17 '15 at 12:31
  • Quick and dirty would be this: `message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo().replace(";", ","));` – user432 Jul 17 '15 at 12:36
  • You need to replace ";" to "," Because InternetAddress.parst() parses data by semicolon, and actually required "," – Manish Prajapati Jul 17 '15 at 12:44
  • Thank you, this work for me. What would be other way to do this? – espresso_coffee Jul 17 '15 at 12:44
  • @user3023588 The other way would be to enter correct data into the database in the first place. All the specifications for email use ',' as list delimiter. Microsoft Outlook's GUI (and only the GUI) uses ';', which I have seen create confusion for people, especially when they then use any other email software and ';' does not work like in Outlook's GUI. – dsh Jul 17 '15 at 14:05
  • Thanks! This works fine. I have one more question for you if you can help. How I can update my database table after I sent my email? I want to update my Sent On field in database with time/date when email has been sent. I do not know where I should implement that code inside of mine. Thanks in advance. – espresso_coffee Jul 17 '15 at 14:25

1 Answers1

24

By default it parse with comma(,) separated email addresses and not with semicolon (;),

InternetAddress[] parse = InternetAddress.parse("abc@gmail.com,pqr@gmail.com");
System.out.println(parse[0].getAddress());

OUTPUT:

abc@gmail.com
akash
  • 22,664
  • 11
  • 59
  • 87