How to send html email java mail

To send an HTML email using JavaMail, you can follow these steps:

  1. Create a MimeMessage object:
    MimeMessage message = new MimeMessage(session);
  2. Set the From and To addresses:
    message.setFrom(new InternetAddress("[email protected]"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
  3. Create a MimeMultipart object to hold the HTML content:
    MimeMultipart multipart = new MimeMultipart();
  4. Create a BodyPart object to hold the HTML content:
    BodyPart htmlPart = new MimeBodyPart();
  5. Set the Content-Type header of the BodyPart object to text/html:
    htmlPart.setHeader("Content-Type", "text/html; charset=UTF-8");
  6. Set the HTML content of the BodyPart object:
    htmlPart.setContent("<html><body><h1>Hello World!</h1></body></html>", "text/html; charset=UTF-8");
  7. Add the BodyPart object to the MimeMultipart object:
    multipart.addBodyPart(htmlPart);
  8. Set the MimeMessage object to use the MimeMultipart object:
    message.setContent(multipart);
  9. Set the subject of the email:
    message.setSubject("Hello World!");
  10. Send the email:
    Transport.send(message);

    Here is the complete code:

    
    import javax.mail.*;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.internet.MimeBodyPart;

public class SendHtmlEmail { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "your-smtp-host"); props.put("mail.smtp.port", "your-smtp-port"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true");

    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("your-email", "your-password");
        }
    });

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
    message.setSubject("Hello World!");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setHeader("Content-Type", "text/html; charset=UTF-8");
    htmlPart.setContent("<html><body><h1>Hello World!</h1></body></html>", "text/html; charset=UTF-8");
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);

    Transport.send(message);
}

}


Make sure to replace the placeholders (`your-smtp-host`, `your-smtp-port`, `your-email`, and `your-password`) with your actual SMTP server settings and email credentials.