JAVA MAIL is a tool that uses existing email accounts to send emails. For example, I register an email account with NetEase. Through the control of JAVA Mail, I can not log in to NetEase mailbox in person, so that the program can automatically use NetEase mailbox to send emails. This mechanism is widely used in registration activation and spam sending.
The general process of sending Java mail is as follows:
1. Build a specific class inherited from javax.mail.Authenticator, and override the getPasswordAuthentication() method inside. This class is used as login verification to ensure that you have the right to send emails to this mailbox.
2. Build a properties file, which stores parameters such as SMTP server address.
3. Create a javax.mail.Session through the built properties file and the javax.mail.Authenticator concrete class. The creation of a Session is equivalent to logging into the email address. The rest is naturally a new email.
4. To build the email content, it is generally a javax.mail.internet.MimeMessage object, and specify the sender, recipient, subject, content, etc.
5. Use the javax.mail.Transport tool class to send emails.
Below is the code I encapsulated, and the comments are also quite detailed.
1. First, it is a specific class inherited from javax.mail.Authenticator. The getPasswordAuthentication() method is to build a PasswordAuthentication object and return it, which is a bit confusing to understand the design intentions of JAVA Mail. It may be that javax.mail.Authenticator provides us with additional verification measures to ensure security.
package com.mzule.simplemail; import javax.mail.Authenticator;import javax.mail.PasswordAuthentication; /** * Server mailbox login verification* * @author MZULE * */public class MailAuthenticator extends Authenticator { /** * Username (login mailbox) */ private String username; /** * Password*/ private String password; /** * Initialize mailbox and password* * @param username mailbox* @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. Email sending class , the remaining steps are implemented in this class. SimpleMail in the code is a POJO that encapsulates the subject and content of the email. I feel that it is not appropriate to include both topic and content in a method parameter, so I overloaded this method. Also, because the SMTP server addresses of most mailboxes can be calculated by email addresses. For simplicity, a constructor that does not require an SMTP server address is provided.
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, can be sent in single or mass. * * @author MZULE * */public class SimpleMailSender { /** * Props file for sending mail*/ private final transient Properties props = System.getProperties(); /** * Mail server login verification*/ private transient MailAuthenticator authenticator; /** * Email session */ private transient Session session; /** * Initialize the mail sender* * @param smtpHostName * SMTP mail server address* @param username * Username (address) for sending mail * @param password * Password for sending email*/ public SimpleMailSender(final String smtpHostName, final String username, final String password) { init(username, password, smtpHostName); } /** * Initialize the email sender* * @param username * Username (address) of the email sending emails, and use this to resolve the SMTP server address* @param password * Password for sending email*/ public SimpleMailSender(final String username, final String password) { //Solve the smtp server through the email address, which works for most mailboxes final String smtpHostName = "smtp." + username.split("@")[1]; init(username, password, smtpHostName); } /** * Initialization* * @param username * Username (address) for sending the email * @param password * Password* @param smtpHostName * SMTP host address*/ private void init(String username, String password, String smtpHostName) { // Initialize props props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", smtpHostName); // Verify authenticator = new MailAuthenticator(username, password); // Create session session = Session.getInstance(props, authenticator); } /** * Send email* * @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 mail final MimeMessage message = new MimeMessage(session); // Set sender message.setFrom(new InternetAddress(authenticator.getUsername())); // Set recipient message.setRecipient(RecipientType.TO, new InternetAddress(recipient)); // Set topic message.setSubject(subject); // Set the message content message.setContent(content.toString(), "text/html;charset=utf-8"); // Send Transport.send(message); } /** * Bulk email* * @param recipients * Recipients* @param subject * Subject* @param content * Content* @throws AddressException * @throws MessagingException */ public void send(List<String> recipients, String subject, Object content) throws AddressException, MessagingException { // Create mime type mail final MimeMessage message = new MimeMessage(session); // Set the sender message.setFrom(new InternetAddress(authenticator.getUsername())); // Set the recipient 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 topic message.setSubject(subject); // Set the mail content message.setContent(content.toString(), "text/html;charset=utf-8"); // Send Transport.send(message); } /** * Send email* * @param recipient * Recipient email address* @param mail * Mail object* @throws AddressException * @throws MessagingException */ public void send(String recipient, SimpleMail mail) throws AddressException, MessagingException { send(recipient, mail.getSubject(), mail.getContent()); } /** * Bulk email* * @param recipients * Recipients* @param mail * Mail object* @throws AddressException * @throws MessagingException */ public void send(List<String> recipients, SimpleMail mail) throws AddressException, MessagingException { send(recipients, mail.getSubject(), mail.getContent()); } }3. Calling the above mailbox sender can build a factory class . The factory class can encapsulate the creation process, so it becomes very convenient to obtain the mailbox username by reading the configuration file. The following code was written when I was writing Observer mode, and it just briefly demonstrated 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 mailbox*/ private static SimpleMailSender serviceSms = null; /** * Get mailbox* * @param type Mailbox type* @return mailbox that matches the type*/ public static SimpleMailSender getSender(MailSenderType type) { if (type == MailSenderType.SERVICE) { if (serviceSms == null) { serviceSms = new SimpleMailSender("[email protected]", "hidden"); } return serviceSms; } return null; } }4. Send email or the code in Observer Mode DEMO, huh.
package com.mzule.dp.observer.observer; import java.util.ArrayList;import java.util.List;import java.util.Observable;import java.util.Observable;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 email SimpleMailSender sms = MailSenderFactory .getSender(MailSenderType.SERVICE); List<String> recipients = new ArrayList<String>(); recipients.add("[email protected]"); recipients.add("[email protected]"); try { for (String recipient : recipients) { sms.send(recipient, "Price Change", "Items You Pay attention to" + product.getName() + "The price has been reduced, from " + product.getPrice() + "yuan to " + price + "yuan, the decline reached" + decrease + "yuan RMB. Shop quickly. "); } } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } } } } 5. Check whether the email has been sent successfully.
The above is the entire process of sending Java emails, and I hope it will be helpful to everyone's learning.