Catalog
Java implements email function
Preface
The application scenarios of e-mail are very extensive, such as new users joining, sending preferential lists instantly, retrieving passwords through e-mail, monitoring background programs, and abnormal automatic e-mail notifications.
Taking Netease mailbox as an example, this paper implements the function of sending mail through Java code.
development environment
Please refer to: Building sub-module project based on SpringBook
Code
-
pom.xml introduces dependencies
<properties> <java.version>1.8</java.version> <!-- Your other dependencies... --> <javax.mail.version>1.6.0</javax.mail.version> </properties> <dependencies> <!-- Your other dependencies... --> <!-- Send short messages --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>${javax.mail.version}</version> </dependency> </dependencies>
-
Sending Mail Tool Class
package com.wayne.common.utils; import com.wayne.common.entity.CmsMailConfig; import com.wayne.common.vo.MailVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * Sending Mail Tool Class * @author Wayne * @date 2019/6/19 */ @Component public class MailUtils { /** * Send mail * @param isSingle Whether single: true-single false-group * @param mailVo Mail content * @param sendTime Delivery time, if null, means immediate delivery * @param mailConfig Sender Information and Authorization */ public void sendMail(Boolean isSingle, MailVo mailVo, Date sendTime, CmsMailConfig mailConfig) throws MessagingException { Session session = this.authenticationMail(); MimeMessage message = getMimeMessage(isSingle, session, mailConfig.getMailAccount(), mailVo.getRecipients()); message = getContent(message, mailVo.getMailTiTle(), mailVo.getMailContent(), sendTime); Transport transport = session.getTransport(); transport.connect(mailConfig.getMailAccount(), mailConfig.getMailLicense()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } /** * Check the contents of the mail sent */ private MimeMessage getContent(MimeMessage message, String messageTitle, String messageContent, Date sendTime) throws MessagingException { if (null == messageTitle) { throw new MessagingException("Mail Title Cannot Be Empty"); } if (null == messageContent) { throw new MessagingException("Mail content cannot be empty"); } sendTime = sendTime == null ? new Date() : sendTime; message.setSubject(messageTitle, "UTF-8"); message.setContent(messageContent, "text/html;charset=UTF-8"); message.setSentDate(sendTime); return message; } /** * Verify authentication information */ private Session authenticationMail() throws MessagingException { Session session; try { Properties props = new Properties(); //Setting User Authentication Mode props.setProperty("mail.smtp.auth", "true"); //Setting up Transport Protocol props.setProperty("mail.transport.protocol", "smtp"); //Setting the sender's SMTP server address props.setProperty("mail.smtp.host", "smtp.163.com"); session = Session.getInstance(props); session.setDebug(true); } catch (Exception e) { e.printStackTrace(); throw new MessagingException("Authentication failure"); } return session; } /** * @param isSingle Is it single? * <P>true-Send an email to a designated recipient, such as: retrieve password, login validation * <P>false-Send e-mails to multiple recipients, such as promotional events * <P>In mass distribution, multiple recipients are separated by English commas', ' * @param senderAddress sender address * @param recipientAddress Addressee address */ private MimeMessage getMimeMessage(Boolean isSingle, Session session, String senderAddress, String recipientAddress) throws MessagingException { MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(senderAddress)); } catch (MessagingException e) { throw new MessagingException("Sender address error"); } /* Setting the addressee address MimeMessage.RecipientType.TO:Send out MimeMessage.RecipientType.CC: CC MimeMessage.RecipientType.BCC: bcc */ if (isSingle) { message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress)); } else { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientAddress)); } return message; } }
-
Mail Content Object-MailVo
package com.wayne.common.vo; import lombok.Data; /** * @author Wayne * @date 2019/6/24 */ @Data public class MailVo { /** * Mail Title */ private String mailTiTle; /** * Mail content */ private String mailContent; /** * Recipients (people) */ private String recipients; }
-
Sender Information and Authorization
Note: Here I assume that there are multiple senders and they are uncertain. I can dynamically add and choose which sender to send, so I store the sender information in the database. If the sender of your application is fixed, it can be written here in the project or in the configuration file!
We need to enter a password to log in to our mailbox account when sending mail normally. And sending mail through the program does not require password login, but uses authorization code. Netease mailbox authorization code is obtained in the following way
- Enabling Authorization
- Authorization Code
package com.wayne.common.entity; import lombok.Data; import javax.persistence.*; @Data @Table(name = "cms_mail_config") public class CmsMailConfig { /** * Primary key */ @Id @Column(name = "MAIL_ID") private Integer mailId; /** * Mail account */ @Column(name = "MAIL_ACCOUNT") private String mailAccount; /** * Authorization code */ @Column(name = "MAIL_LICENSE") private String mailLicense; /** * Status, 0: Used, 1: Not Used */ @Column(name = "IS_USE") private String isUse; /** * Whether to delete, 0:No, 1:Yes */ @Column(name = "IS_DELETE") private String isDelete; /** * Creator ID */ @Column(name = "CREATE_ADMIN_ID") private Integer createAdminId; @Column(name = "EXTEND1") private String extend1; @Column(name = "EXTEND2") private String extend2; @Column(name = "EXTEND3") private String extend3; @Column(name = "EXTEND4") private String extend4; @Column(name = "EXTEND5") private String extend5; @Column(name = "EXTEND6") private String extend6; }
-
Service
@Override public ResponseBean sendMails(MailVo mailVo) { if (null == mailVo) { return ResponseBean.createInstance(Boolean.FALSE, 400, "Parametric anomaly"); } // Get the sender configuration currently in use List<CmsMailConfig> mailConfigList = mailConfigMapper.selectCurrUseMailConfig(); if (null == mailConfigList || mailConfigList.size() != 1) { return ResponseBean.createInstance(Boolean.FALSE, 400, "Parametric anomaly"); } try { // Send mail mailUtils.sendMail(Boolean.FALSE, mailVo, null, mailConfigList.get(0)); return ResponseBean.createInstance(); } catch (Exception e) { e.printStackTrace(); } return ResponseBean.createInstance(Boolean.FALSE, 400, "Parametric anomaly"); }
-
Controller
@PostMapping("/mail/sendMails") public ResponseBean sendMails(MailVo mailVo) { return mailService.sendMails(mailVo); }
Effect
Send here for manual transmission, mainly experience the code function. Specific application scenarios can be adapted to the actual production environment. For example, by combining the timer task, the report is sent regularly every day; when the user's login address is not the usual address, the user is automatically notified by email; when the ordinary user logs in, the email is triggered to send to the administrator, etc.
Concluding remarks
I have opened a public number. Welcome to irrigation.