Sending email using JSP

Well offhand I would say there is an authentication issue when trying to connect. You are not providing any username or password, unless your exchange server doesn’t require username and password.


UPDATE: If using JDK 7 see the following post, it resolved this issue:

Defect – JDK7 Permission Denied with Sockets when using VPN

“More digging around and it seems the VPN client has IPv6 disabled which is causing issues with JDK7. If I use the following flag -Djava.net.preferIPv4Stack=true I no longer see the errors. Is this workaround expected or is this an issue?”


public class MailTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws MessagingException {
        String host = "smtp.gmail.com";
        String to = "[email protected]";
        String from = "[email protected]";
        String subject = "test";
        String messageText = "body test";

        Properties props = System.getProperties();
        props.put("mail.host", host);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", "25");

        // If using authentication, otherwise comment out
        props.put("mail.smtp.auth", "true");

        // Gmail requires TLS, your server may not
        props.put("mail.smtp.starttls.enable", "true");

        Session mailSession = Session.getDefaultInstance(props, null);

        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setText(messageText);

        Transport transport = mailSession.getTransport("smtp");

        //connect with authentication
        //transport.connect(host,"myUsername" , "myPassword");

        //connect without authentication
        transport.connect();
        transport.sendMessage(msg, address);

        transport.close();

        System.out.println("Mail was sent to " + to);
        System.out.println(" from " + from);
        System.out.println(" using host " + host + ".");

    }
}

Leave a Comment