Java implements the smtp based method of sending mail

  • 2020-04-01 04:00:51
  • OfStack

This article illustrates a Java implementation of smtp-based mail delivery. Share with you for your reference. The specific implementation method is as follows:


import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
public class MailUtil {
 private static Logger logger = Logger.getLogger(MailUtil.class);
 
 public static void send(String smtp, final String user,
   final String password, String subject, String content, String from,
   String to) {
  try {
   Properties props = new Properties();
   props.put("mail.smtp.host", smtp);
   props.put("mail.smtp.auth", "true");
   Session ssn = Session.getInstance(props, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(user, password);
    }
   });
   MimeMessage message = new MimeMessage(ssn);
   //Create a new message object from the mail session
   InternetAddress fromAddress = new InternetAddress(from);
   //The sender's email address
   message.setFrom(fromAddress);
   //Set sender
   InternetAddress toAddress = new InternetAddress(to);
   //The recipient's email address
   message.addRecipient(Message.RecipientType.TO, toAddress);
   //Set recipient
   message.setSubject(subject);
   //Set the title
   message.setText(content);
   //Set the content
   message.setSentDate(new Date());
   //Set the mailing time
   Transport transport = ssn.getTransport("smtp");
   transport.connect(smtp, user, password);
   transport.sendMessage(message, message
     .getRecipients(Message.RecipientType.TO));
   // transport.send(message);
   transport.close();
   logger.info(" Email sent successfully ");
  } catch (Exception e) {
   logger.warn(" Mail delivery failed ", e);
  }
 }
}

I hope this article has been helpful to your Java programming.


Related articles: