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 SendEmail { public static void main(String[] args) { // Mention the recipients email address String to = "splessons@gmail.com"; // Mention the senders email address String from = "splessons11@gmail.com"; final String username = "splessons";//change accordingly final String password = "******";//change accordingly // Assuming that sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // To get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Creating a default Mime Message object. Message message = new MimeMessage(session); // To set header filed message.setFrom(new InternetAddress(from)); // To set header filed message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // To set subject to header filed message.setSubject("Test Subject"); // To set the actual message message.setText("Hello, this is sample for to check send " + "email using JavaMailAPI "); // To send message Transport.send(message); System.out.println("message send"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
Output
message send