Some times you need to send an email from your java application through a SMTP server. here is how you can do it simply using JavaMail API:

1- Instantiate  properties object, that contains the host name and authentication.

2- Instantiate Java Mail Session.

3- Create and fill you message.

4- Get Java Mail Transporter.

5- Connect the Transporter.

6- Send the message by the Transporter.

and here is the code:

/* create properties object */

Properties properties = new Properties();
properties.setProperty(“mail.smtp.host”, “smtp.mailserver.com”);
properties.setProperty(“mail.smtp.auth”, “true”);

/* get session */

Session session = Session.getDefaultInstance(properties, null);

/* create and fill the message */

MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(“sender@company.com”));
message.addRecipient(RecipientType.TO, new InternetAddress(“user@company.com”));
message.addRecipient(RecipientType.CC, new InternetAddress(“user@mail.com”));
message.setSubject(“testing java mail again and again!!!”);
message.setText(“Salam there, \nThis is a test from java mail”);

/* get transport */

Transport transport = session.getTransport(“smtp”);

/* connect to smtp server */
transport.connect(“smtp.mailserver.com”, “username”, “password”);

/* send the message to the recipients */
transport.sendMessage(message, message.getAllRecipients());
System.out.println(“message sent successfuly”);
} catch (AddressException e) {

e.printStackTrace();
} catch (MessagingException e) {

e.printStackTrace();
}

and enjoy sending mails from you application

Advertisements