Send email using java mail api
Here is an example of how to send an email using the Java Mail API:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) {
// Set the properties
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a session
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "your-password");
}
});
// Create a message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Test Email");
message.setText("This is a test email sent using Java Mail API");
// Send the message
Transport.send(message);
}
}
This code sets up a session with the Gmail SMTP server using the Session
class and the Authenticator
class. It then creates a MimeMessage
object and sets the from address, recipient address, subject, and text of the message. Finally, it sends the message using the Transport
class.
You'll need to replace the placeholders with your own email address and password, as well as the recipient's email address.
Note: Make sure to enable less secure apps in your Google account settings if you're using Gmail.
Also, you can use Transport.send(message)
to send the message asynchronously, or you can use message.saveChanges()
to save the message and then use Transport.send(message)
to send it.
You can also use Multipart
to send HTML emails with attachments.
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This is a test email sent using Java Mail API");
multipart.addBodyPart(textPart);
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>This is a test email sent using Java Mail API</body></html>", "text/html");
multipart.addBodyPart(htmlPart);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Test Email");
message.setContent(multipart);
Transport.send(message);
You can also use FileDataSource
to attach files to the email.
FileDataSource fileDataSource = new FileDataSource("path/to/file.txt");
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
multipart.addBodyPart(attachmentPart);
Make sure to handle exceptions properly, and also make sure to close the Session
and Transport
objects when you're done with them.