How to send html email java mail
To send an HTML email using JavaMail, you can follow these steps:
- Create a
MimeMessage
object:MimeMessage message = new MimeMessage(session);
- Set the
From
andTo
addresses:message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
- Create a
MimeMultipart
object to hold the HTML content:MimeMultipart multipart = new MimeMultipart();
- Create a
BodyPart
object to hold the HTML content:BodyPart htmlPart = new MimeBodyPart();
- Set the
Content-Type
header of theBodyPart
object totext/html
:htmlPart.setHeader("Content-Type", "text/html; charset=UTF-8");
- Set the HTML content of the
BodyPart
object:htmlPart.setContent("<html><body><h1>Hello World!</h1></body></html>", "text/html; charset=UTF-8");
- Add the
BodyPart
object to theMimeMultipart
object:multipart.addBodyPart(htmlPart);
- Set the
MimeMessage
object to use theMimeMultipart
object:message.setContent(multipart);
- Set the subject of the email:
message.setSubject("Hello World!");
- 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.