Send email with JavaMail

Simple email:

import javax.mail.*;
import javax.mail.internet.*;

import java.util.Properties;

class SimpleMail {
    public static void main(String[] args) throws Exception{
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "mymail.server.org");
      props.setProperty("mail.user", "emailuser");
      props.setProperty("mail.password", "");

      Session mailSession = Session.getDefaultInstance(props, null);
      Transport transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setSubject("Testing javamail plain");
      message.setContent("This is a test", "text/plain");
      message.addRecipient(Message.RecipientType.TO,
           new InternetAddress("maixuanviet.com@gmail.com"));

      transport.connect();
      transport.sendMessage(message,
          message.getRecipients(Message.RecipientType.TO));
      transport.close();
    }
}

HTML Email:

import javax.mail.*;
import javax.mail.internet.*;

import java.util.Properties;

class SimpleHTMLMail {
    public static void main(String[] args) throws Exception{
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "mymail.server.org");
      props.setProperty("mail.user", "emailuser");
      props.setProperty("mail.password", "");

      Session mailSession = Session.getDefaultInstance(props, null);
      Transport transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setSubject("Testing javamail html");
      message.setContent
         ("This is a test <b>HOWTO<b>", "text/html; charset=ISO-8859-1");
      message.addRecipient(Message.RecipientType.TO,
         new InternetAddress("maixuanviet.com@gmail.com"));

      transport.connect();
      transport.sendMessage(message,
         message.getRecipients(Message.RecipientType.TO));
      transport.close();
    }
}

Email with attachment:

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;

import java.util.Properties;

class SimpleMailWithAttachment {
    public static void main(String[] args) throws Exception{
      boolean debug = false;
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "mymail.server.org");
      props.setProperty("mail.user", "emailuser");
      props.setProperty("mail.password", "");

      Session mailSession = Session.getDefaultInstance(props, null);
      mailSession.setDebug(debug);
      Transport transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setSubject("Testing javamail with attachment");

      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setContent("<h1>Check attachment</h1>", "text/html");

      MimeBodyPart attachFilePart = new MimeBodyPart();
      FileDataSource fds = 
          new FileDataSource("SimpleMailWithAttachment.java");
      attachFilePart.setDataHandler(new DataHandler(fds));
      attachFilePart.setFileName(fds.getName());

      Multipart mp = new MimeMultipart();
      mp.addBodyPart(textPart);
      mp.addBodyPart(attachFilePart);

      message.setContent(mp);
      message.addRecipient(Message.RecipientType.TO,
          new InternetAddress("maixuanviet.com@gmail.com"));

      transport.connect();
      transport.sendMessage(message,
          message.getRecipients(Message.RecipientType.TO));
      transport.close();
    }
}

Done! Happy Coding!

Related posts:

Java Program to Implement Sorted Singly Linked List
Unsatisfied Dependency in Spring
Call Methods at Runtime Using Java Reflection
Java Program to Implement the Monoalphabetic Cypher
Introduction to Spring Security Expressions
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Inject Parameters into JUnit Jupiter Unit Tests
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Binary Numbers in Java
HashMap trong Java hoạt động như thế nào?
Spring NoSuchBeanDefinitionException
Introduction to Liquibase Rollback
Java Program to Perform Left Rotation on a Binary Search Tree
Servlet 3 Async Support with Spring MVC and Spring Security
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Spring Security OAuth Login with WebFlux
Composition, Aggregation, and Association in Java
Anonymous Classes in Java
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
How to Read HTTP Headers in Spring REST Controllers
Java Program to Implement ConcurrentLinkedQueue API
Mix plain text and HTML content in a mail
Java Program to Implement Fermat Factorization Algorithm
Java Program to Implement Double Order Traversal of a Binary Tree
Guide to the Fork/Join Framework in Java
Spring JDBC
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Spring Boot - Google Cloud Platform
Java Program to Implement Floyd Cycle Algorithm
Java Program to Compute Cross Product of Two Vectors
Tạo ứng dụng Java RESTful Client với thư viện OkHttp
Entity To DTO Conversion for a Spring REST API