Java implements simple mail delivery

  • 2020-05-07 19:34:45
  • OfStack

JAVA MAIL is a tool to send emails by using the existing email account. For example, I registered a mailbox account in netease. Through the control of JAVA Mail, I can automatically send emails by using netease mailbox instead of logging into netease mailbox. This 1 mechanism is widely used for registration activation and spam sending.
The general process of Java email is like this:

1. Build a concrete class that inherits from javax.mail.Authenticator and override the getPasswordAuthentication() method. This class is used as a login check to ensure that you have the right to send messages to the mailbox.

2. Build an properties file, which contains SMTP server address and other parameters.

3. Create one javax.mail.Session by building the properties file and javax.mail.Authenticator concrete class. The creation of Session is equivalent to logging into mailbox 1. The rest, of course, is new mail.

4, build E-mail content, 1 kind is javax mail. internet. MimeMessage object, and specify the sender, recipient, subject, content and so on.

5. Use the javax.mail.Transport utility class to send mail.

The following is the code I encapsulated, and the comments are more detailed.

1. First is a concrete class inherited from javax.mail.Authenticator. The getPasswordAuthentication() method is to build an PasswordAuthentication object and return it, which is a little confusing. The design intention of JAVA Mail is that javax.mail.Authenticator provides us with additional security verification measures.


package com.mzule.simplemail;
 
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
 
/**
 *  Server mailbox login verification 
 * 
 * @author MZULE
 * 
 */
public class MailAuthenticator extends Authenticator {
 
  /**
   *  User name (login email address) 
   */
  private String username;
  /**
   *  password 
   */
  private String password;
 
  /**
   *  Initialize the mailbox and password 
   * 
   * @param username  email 
   * @param password  password 
   */
  public MailAuthenticator(String username, String password) {
  this.username = username;
  this.password = password;
  }
 
  String getPassword() {
  return password;
  }
 
  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(username, password);
  }
 
  String getUsername() {
  return username;
  }
 
  public void setPassword(String password) {
  this.password = password;
  }
 
  public void setUsername(String username) {
  this.username = username;
  }
 
}

2, the mail sending class , where the rest of the steps are implemented. The SimpleMail in the code is an POJO that encapsulates the subject and content of the message. I overloaded the method because I felt it was inappropriate to include both topic and content in one method parameter. Also, because the SMTP server address for most mailboxes can be calculated from the mailbox address, for simplicity, a constructor is provided that does not require the SMTP server address.


package com.mzule.simplemail;
 
import java.util.List;
import java.util.Properties;
 
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
 
/**
 *  Simple mail sender, single, group. 
 * 
 * @author MZULE
 * 
 */
public class SimpleMailSender {
 
  /**
   *  emailing props file 
   */
  private final transient Properties props = System.getProperties();
  /**
   *  Mail server login verification 
   */
  private transient MailAuthenticator authenticator;
 
  /**
   *  email session
   */
  private transient Session session;
 
  /**
   *  Initializes the mail sender 
   * 
   * @param smtpHostName
   *        SMTP Mail server address 
   * @param username
   *         The user name from which the message was sent ( address )
   * @param password
   *         The password to send the message 
   */
  public SimpleMailSender(final String smtpHostName, final String username,
    final String password) {
  init(username, password, smtpHostName);
  }
 
  /**
   *  Initializes the mail sender 
   * 
   * @param username
   *         The user name from which the message was sent ( address ) And interpret it accordingly SMTP Server address 
   * @param password
   *         The password to send the message 
   */
  public SimpleMailSender(final String username, final String password) {
  // Resolve by email address smtp Server, which works for most mailboxes 
  final String smtpHostName = "smtp." + username.split("@")[1];
  init(username, password, smtpHostName);
 
  }
 
  /**
   *  Initialize the 
   * 
   * @param username
   *         The user name from which the message was sent ( address )
   * @param password
   *         password 
   * @param smtpHostName
   *        SMTP The host address 
   */
  private void init(String username, String password, String smtpHostName) {
  //  Initialize the props
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.host", smtpHostName);
  //  validation 
  authenticator = new MailAuthenticator(username, password);
  //  create session
  session = Session.getInstance(props, authenticator);
  }
 
  /**
   *  Send E-mail 
   * 
   * @param recipient
   *         Recipient email address 
   * @param subject
   *         Email subject 
   * @param content
   *         Email content 
   * @throws AddressException
   * @throws MessagingException
   */
  public void send(String recipient, String subject, Object content)
    throws AddressException, MessagingException {
  //  create mime Type the mail 
  final MimeMessage message = new MimeMessage(session);
  //  Set the sender 
  message.setFrom(new InternetAddress(authenticator.getUsername()));
  //  Set recipient 
  message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
  //  Set the theme 
  message.setSubject(subject);
  //  Set email content 
  message.setContent(content.toString(), "text/html;charset=utf-8");
  //  send 
  Transport.send(message);
  }
 
  /**
   *  Mass email 
   * 
   * @param recipients
   *         The recipient 
   * @param subject
   *         The theme 
   * @param content
   *         content 
   * @throws AddressException
   * @throws MessagingException
   */
  public void send(List<String> recipients, String subject, Object content)
    throws AddressException, MessagingException {
  //  create mime Type the mail 
  final MimeMessage message = new MimeMessage(session);
  //  Set the sender 
  message.setFrom(new InternetAddress(authenticator.getUsername()));
  //  Set recipients 
  final int num = recipients.size();
  InternetAddress[] addresses = new InternetAddress[num];
  for (int i = 0; i < num; i++) {
    addresses[i] = new InternetAddress(recipients.get(i));
  }
  message.setRecipients(RecipientType.TO, addresses);
  //  Set the theme 
  message.setSubject(subject);
  //  Set email content 
  message.setContent(content.toString(), "text/html;charset=utf-8");
  //  send 
  Transport.send(message);
  }
 
  /**
   *  Send E-mail 
   * 
   * @param recipient
   *         Recipient email address 
   * @param mail
   *         Email object 
   * @throws AddressException
   * @throws MessagingException
   */
  public void send(String recipient, SimpleMail mail)
    throws AddressException, MessagingException {
  send(recipient, mail.getSubject(), mail.getContent());
  }
 
  /**
   *  Mass email 
   * 
   * @param recipients
   *         The recipient 
   * @param mail
   *         Email object 
   * @throws AddressException
   * @throws MessagingException
   */
  public void send(List<String> recipients, SimpleMail mail)
    throws AddressException, MessagingException {
  send(recipients, mail.getSubject(), mail.getContent());
  }
 
}

3, call the mailbox sender above, you can build a factory class , the factory class can encapsulate the creation process, so by reading the configuration file to get the mailbox user name, password will become 10 points convenient. The following code, which I wrote when I was writing observer mode, simply demonstrates the factory class.


package com.mzule.dp.observer.factory;
 
import com.mzule.dp.observer.constant.MailSenderType;
import com.mzule.simplemail.SimpleMailSender;
 
/**
 *  Outbox factory 
 * 
 * @author MZULE
 * 
 */
public class MailSenderFactory {
 
  /**
   *  Service email 
   */
  private static SimpleMailSender serviceSms = null;
 
  /**
   *  Access to email 
   * 
   * @param type  The mailbox type 
   * @return  Type of mailbox 
   */
  public static SimpleMailSender getSender(MailSenderType type) {
  if (type == MailSenderType.SERVICE) {
    if (serviceSms == null) {
    serviceSms = new SimpleMailSender("invisible@126.com",
      "hidden");
    }
    return serviceSms;
  }
  return null;
  }
 
}

4, send email , or the code in observer mode DEMO, whoop.


package com.mzule.dp.observer.observer;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
 
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
 
import com.mzule.dp.observer.constant.MailSenderType;
import com.mzule.dp.observer.factory.MailSenderFactory;
import com.mzule.dp.observer.po.Product;
import com.mzule.simplemail.SimpleMailSender;
 
public class ProductPriceObserver implements Observer {
 
  @Override
  public void update(Observable obj, Object arg) {
  Product product = null;
  if (obj instanceof Product) {
    product = (Product) obj;
  }
  if (arg instanceof Float) {
    Float price = (Float) arg;
    Float decrease = product.getPrice() - price;
    if (decrease > 0) {
    //  Send E-mail 
    SimpleMailSender sms = MailSenderFactory
      .getSender(MailSenderType.SERVICE);
    List<String> recipients = new ArrayList<String>();
    recipients.add("invisible@qq.com");
    recipients.add("invisible@gmail.com");
    try {
      for (String recipient : recipients) {
      sms.send(recipient, " Price changes ", " Items of your concern "
        + product.getName() + " Reduced the price, by "
        + product.getPrice() + " Yuan to " + price + " Yuan, a drop of up to "
        + decrease + " RMB yuan. Go shopping. ");
      }
    } catch (AddressException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
    }
  }
  }
 
}

5. Check if the email was sent successfully.
Above is the whole process of java email, I hope to help you with your study.


Related articles: