What is the recommended way to send email programmatically with Java?
Yes, I will send e-mail to you with Java.
Give me your email id :)
Just kidding:
- import java.util.Properties;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Session;
- import javax.mail.Transport;
- importjavax.mail.internet.AddressException;
- importjavax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class SendMailTLS {
- public static void main(String[] args) {
- // To address
- String to = "[email protected]";
- // If any CC email ids
- String cc = "[email protected]";
- // If any BCC email ids
- String bcc = "[email protected]";
- // Email Subject
- String subject = "Java Discover";
- // Email content
- String emailText = "Hi All, Welcome to Java Mail API";
- // Sending Email using Gmail SMTP
- sendEmail(to, cc, bcc, subject, emailText);
- }
- public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) {
- // From address (Need Gmail ID)
- String from = "[email protected]";
- // Password of from address
- String password = "from_password";
- // Gmail host address
- String host = "smtp.gmail.com";
- Properties props = System.getProperties();
- props.put("mail.smtp.host", host);
- props.put("mail.smtp.socketFactory.port", "465");
- props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.port", "465");
- props.put("mail.smtp.user", from);
- props.put("password", password);
- Session session = Session.getDefaultInstance(props, null);
- MimeMessage msg = newMimeMessage(session);
- try {
- msg.setFrom(newInternetAddress(from));
- // Adding To address
- msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
- // Adding CC email id
- msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
- // Adding BCC email id
- msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
- msg.setSubject(subject);
- msg.setText(emailText);
- Transport transport = session.getTransport("smtp");
- transport.connect(host, from, password);
- transport.sendMessage(msg, msg.getAllRecipients());
- transport.close();
- System.out.println("Email was sent successfully.....");
- } catch (AddressException e) {
- e.printStackTrace();
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- }
- }