Java send mail example
Here is a simple example of how to send an email using Java:
Using JavaMail API
You need to add the JavaMail API to your project. You can download it from here.
Here is the example code:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// Set the email 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() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "your-password");
}
});
// Create a message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Test email");
message.setText("This is a test email");
// Send the message
Transport.send(message);
}
}
Using Apache Commons Email
You need to add the Apache Commons Email library to your project. You can download it from here.
Here is the example code:
import org.apache.commons.mail.DefaultAuthenticatingMailSession;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
public class SendEmail {
public static void main(String[] args) {
// Set the email properties
DefaultAuthenticatingMailSession mailSession = new DefaultAuthenticatingMailSession("smtp.gmail.com", 587, "[email protected]", "your-password");
// Create an email
Email email = new SimpleEmail();
email.setSession(mailSession);
email.setFrom("[email protected]");
email.setSubject("Test email");
email.setMsg("This is a test email");
// Add a recipient
email.addRecipient("[email protected]");
// Send the email
try {
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
}
Note:
- Replace
"[email protected]"
and"your-password"
with your actual Gmail email and password. - Replace
"[email protected]"
with the email address of the recipient. - Make sure to enable less secure apps in your Google account settings if you're using Gmail.
- You may need to add additional dependencies or configuration depending on your specific use case.