Welcome to the JavaMail API tutorial! In this lesson, we'll learn how to send emails programmatically using the JavaMail API. By the end of this tutorial, you'll be able to integrate email functionality into your Java projects. š
Let's start with the basics!
JavaMail API is a Java library that allows you to send and receive emails from within your Java applications. It's a powerful tool for developers looking to automate email communication.
pom.xml file:<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;Let's write a simple Java program to send an email using the JavaMail API.
public class Main {
public static void main(String[] args) throws Exception {
// Setup the properties
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
// Setup the session
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@gmail.com", "your-password");
}
});
// Setup the message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient-email@example.com"));
message.setSubject("Test Email");
message.setText("Hello, this is a test email sent using JavaMail API.");
// Send the message
Transport.send(message);
System.out.println("Email sent successfully!");
}
}Replace "your-email@gmail.com" and "your-password" with your Gmail email and password. Replace "recipient-email@example.com" with the recipient's email address.
š Note: You might need to allow less secure apps to access your account in your Gmail account settings.
Which Maven dependency should be added to use JavaMail API?
That's it for our first lesson on the JavaMail API! In the next lessons, we'll learn more advanced features like attaching files, handling replies, and error handling. Stay tuned! š
š” Pro Tip: Don't forget to commit and push your code to version control systems like Git to track changes and collaborate with others.
š Note: In real-world projects, you might need to configure additional properties or use different email providers like Yahoo or Outlook.