English English

Javax.Mail - How to send emails in Java

This tutorial will teach you how to create and send e-mails in a Java application. 

The sending of the email will be done through a function which will be created in this tutorial. It is recommended that you add this function in a thread.


You need to have an email account, which will be used to send your emails in this application.

The package "javax.mail" will be used to realize this. You can add it to your maven project ("pom.xml" file):



Authentication class

This class is used to save the username and password to send the email in the function that is mentioned below. Because this is only an example for teaching purposes. In production and real world usage: The username and password should be in a properties file. The password should be hashed.

public class MyMailAuthenticator extends Authenticator {

	public MyMailAuthenticator() {

	public PasswordAuthentication getPasswordAuthentication() {

		String emailUsernameString = "YOUR_USERNAME";
		String emailPasswordString = "YOUR_PASSWORD";

		return new PasswordAuthentication(emailUsernameString, emailPasswordString);

Sending email function

This function sends an email with the defined properties. The exception "MessagingException" will be thrown, when the sending of the email failed. The email adress of the email account that is used to send email is defined in the variable "sourceEmail". The variable "attachmentFileName" defines the name of the attachment file. E.g.: "attachment.pdf". The absolute path of the attachment is defined in the variable "attachmentFilePath". 

    public void sendEmail(String sourceEmail, String destinationEmail, String attachmentFileName, String attachmentFilePath) throws MessagingException  {

        MyMailAuthenticatorauthentication = new MyMailAuthenticator();

        //Email server settings
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", "smtp.mail.tld");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.auth", "true");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = null;
        session = Session.getDefaultInstance(properties, authentication);
        //Create a new email
        Message emailMessage = new MimeMessage(session);
        emailMessage.setFrom(new InternetAddress(sourceEmail));
        emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationEmail));
        emailMessage.setSubject("A test email");
        Multipart messageParts = new MimeMultipart();
        // Body email
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("Hello. This is a test email");
        // Create email attachment
        DataSource attachmentSource = new FileDataSource(attachmentFilePath);
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(attachmentSource));

        //Set email content and send email

The email server that will be used to send your emails in this application is defined in the variable "properties". In this case the email is encrypted with SSL, that's why you have to use the port "465".

The meta settings (from email address, to email address and subject) of the email is defined in the variable "emailMessage".
Message.RecipientType.TO puts the recepient's address in the "CC" field. If you want to use "BCC" (blind carbon copy", then you can use "Message.RecipientType.BCC" instead.

The content of the email is defined in the variable "messageBodyPart". The attachment is defined in the variable attachmentSource. The method "setDataHandler" loads the file from the defined attachment path. Method "setFileName" sets the name of the attachment file.
The email content and loaded email attachment are added through the method "addBodyPart".

If an error happening during the process of sending an email, then the method "Transport.send" will throw the exception "MessagingException". There you can find the reason for the error and error message.

More info about Javax.Mail:

Usamos cookies en nuestro sitio web. Algunas de ellas son esenciales para el funcionamiento del sitio, mientras que otras nos ayudan a mejorar el sitio web y también la experiencia del usuario (cookies de rastreo). Puedes decidir por ti mismo si quieres permitir el uso de las cookies. Ten en cuenta que si las rechazas, puede que no puedas usar todas las funcionalidades del sitio web.