Send simple email using JavaMail API

We are explaining here an example of sending simple email using JavaMail API.

Steps of sending simple email using JavaMail API:

    1. Get a session instance from getDefaultInstance() or getInstance() method of Session class.
    2. Create a message we have to pass session object in MimeMessage class constructor.
    3. Use the InternetAddress class to set the information of sender and recipient.
    4. Complose the message by using MimeMessage class methods like setFrom(Address address), addRecipients(Message.RecipientType type, String addresses), setSubject(String subject), setText(String textmessage) etc.
    5. Use send() method of javax.mail.Transport class to send the message.

Example:

SendSimpleEmail.java
import java.util.*;  
import javax.mail.*;
import javax.mail.internet.*;
/**
* This class is used to send simple email.
* @author javawithease
*/

public class SendSimpleEmail {
final String senderEmailId = "jaisingh@javawithease.com";
final String senderPassword = "****";
final String emailSMTPserver = "smtpout.secureserver.net";
 
public SendSimpleEmail(String receiverEmail,
String subject, String messageText) {
 
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", emailSMTPserver);
 
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmailId));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(receiverEmail));
message.setSubject(subject);
message.setText(messageText);
 
Transport.send(message);
System.out.println("Email send successfully.");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error in sending email.");
}
}
 
private class SMTPAuthenticator extends
javax.mail.Authenticator {
public PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(senderEmailId,
senderPassword);
}
}
 
public static void main(String[] args) {
new SendSimpleEmail("javawithease@gmail.com",
"Test Email", "Hi,\n\n This is a test email.");
}
}

Output:

Email send successfully.

No comments: