Java Hosting - Using Java Mail on our servers

Sending your email with Java is just a few steps away!

Using Java Mail API to send emails from our servers

Here goes example code that you can use to test Java Mail library. After you created mail user in cPanel, simply put this code in your Tomcat's webapps/ROOT/mailtest.jsp and update the variables at the top of the file with yours.

Having sessionDebug set to true will log SMTP(S) session to logs/catalina.out. Get mail.jar from Java Mail website and place it in ROOT/WEB-INF/lib.

<%@ page import="java.util.*, javax.mail.*, javax.mail.internet.*" %>
<%
String host = "mail.domainname.com";
String user = "user@domain.com";
String pass = "xxxxx";
String to = "user@example.com";
String from = "user@domain.com";
String subject = "Dummy subject";
String messageText = "Dummy body";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
// props.put("mail.transport.protocol", "smtps");

// Set SMTP or SMTPS attributes - if you prefer to use SMTPS port see below
props.put("mail.smtp.auth", "true");
// Optionally set non-default port
// props.put("mail.smtp.port", 26);

// If you prefer or need SMTPS (e.g. when sending via Gmail) comment SMTP attributes above and uncomment SMTPS attributes above and below
// props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.port", "465");
// props.put("mail.smtps.ssl.trust", host);

Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
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");
// Transport transport = mailSession.getTransport("smtps");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
%>

Note: You may add multiple recipients to the ‘address’ list. For more information check Java Mail FAQ. Google may mark first login try from a new IP/device as suspected. You will then need to login to Gmail via web and confirm it was you.