What is Spring Boot
Spring Boot is a framework designed to simplify the initial construction configuration and development process of Spring applications. This framework uses specific configuration methods, so that developers do not need to define boilerplate configurations.
The benefits of Spring Boot
1. Simple configuration;
2. Simple encoding;
3. Simple deployment;
4. Simple monitoring;
Overview
Spring Boot integrates a mail server, and using Spring Boot can easily achieve email sending; sort out the recent email sending and precautions for Spring Boot;
Maven package dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId></dependency>
Spring Boot configuration
spring.mail.host=smtp.servie.comspring.mail.username=username//sender's email address spring.mail.password=password//For qq mailbox, the password refers to the sender's authorization code spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=false #Whether to enable encrypted transmission use the protocol verification item spring.mail.properties.mail.smtp.starttls.required=fasle #Whether to enable encrypted transmission use the protocol verification item spring.mail.password is the authorization code that needs to be generated in the mailbox settings, which is not the real password.
Spring code implementation
package com.dbgo.webservicedemo.email;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Component;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File;@Component("emailtool")public class EmailTool { @Autowired private JavaMailSender javaMailSender; public void sendSimpleMail(){ MimeMessage message = null; try { message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setSubject("Title: Send Html content"); StringBuffer sb = new StringBuffer(); sb.append("<h1>Large Title-h1</h1>") .append("<p style='color:#F00'>Red Word</p>") .append("<p style='text-align:right'>right</p>"); helper.setText(sb.toString(), true); FileSystemResource fileSystemResource=new FileSystemResource(new File("D:/76678.pdf")) helper.addAttachment("Electronic invoice", fileSystemResource); javaMailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } }}Send emails under non-Spring Boot:
Maven package dependencies
<dependencies> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency> </dependencies>
DEMO1 code example
package com.justin.framework.core.utils.email;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.util.Date;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.Message.RecipientType;import javax.mail.Message.RecipientType;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.Internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;/** * Use SMTP protocol to send email*/public class sendEmailCode { // Email send protocol private final static String PROTOCOL = "smtp"; // SMTP mail server private final static String HOST = "mail.tdb.com"; // SMTP mail server default port private final static String PORT = "25"; // Whether to require authentication private final static String IS_AUTH = "true"; // Whether to enable debug mode (enable debug mode to print the response message of a question and answer when the client and the server interact) private final static String IS_ENABLED_DEBUG_MOD = "true"; // Sender private static String from = "[email protected]"; // Recipient private static String to = "[email protected]"; private static String senduserName="[email protected]"; private static String senduserPwd="New*2016"; // Initialize the session information connecting to the mail server private static Properties props = null; static { props = new Properties(); props.setProperty("mail.enable", "true"); props.setProperty("mail.transport.protocol", PROTOCOL); props.setProperty("mail.smtp.host", HOST); props.setProperty("mail.smtp.port", PORT); props.setProperty("mail.smtp.auth", IS_AUTH);//Depending on the situation, props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD); } /** * Send simple text mail*/ public static boolean sendTextEmail(String to,int code) throws Exception { try { // Create Session instance object Session session1 = Session.getDefaultInstance(props); // Create MimeMessage instance object MimeMessage message = new MimeMessage(session1); // Set the sender message.setFrom(new InternetAddress(from)); // Set the email subject message.setSubject("Internal Combustion Engine Registration Verification Code"); // Set the recipient message.setRecipient(RecipientType.TO, new InternetAddress(to)); // Set the sending time message.setSentDate(new Date()); // Set the plain text content to the email text message.setText("Your verification code is: "+code+"! The verification code is valid for 10 minutes. Please re-get it after it expires!" + "China Internal Combustion Engine Society"); // Save and generate the final email content message.saveChanges(); // Get the Transport instance object Transport transport = session1.getTransport(); // Open the connection transport.connect("meijiajiang2016", ""); // Pass the message object to the transport object and send the message out transport.sendMessage(message, message.getAllRecipients()); // Close the connection transport.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static void main(String[] args) throws Exception { sendHtmlEmail("[email protected]", 8888); } /** * Send a simple html email*/ public static boolean sendHtmlEmail(String to,int code) throws Exception { // Create Session instance object Session session1 = Session.getInstance(props, new MyAuthenticator()); // Create MimeMessage instance object MimeMessage message = new MimeMessage(session1); // Set the email subject message.setSubject("Internal Combustion Engine Registration"); // Set sender message.setFrom(new InternetAddress(from)); // Set send time message.setSentDate(new Date()); // Set recipient message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); // Set html content to the email body, specify MIME type to text/html type, and specify the character encoding as gbk message.setContent("<div style='width: 600px;margin: 0 auto'><h3 style='color:#003E64; text-align:center; '>Internal combustion engine registration verification code</h3><p style=''>Hello, Dear user:</p><p style='text-indent: 2em'>You are registering an internal combustion engine account. The verification code this time is: "+code+", valid for 10 minutes! If it expires, please re-get it. </p><p style='text-align: right; color:#003E64; font-size: 20px;'>China Internal Combustion Engine Society</p></div>","text/html;charset=utf-8"); //Set the custom sender nickname String nick=""; try { nick=javax.mail.internet.MimeUtility.encodeText("China Internal Combustion Engine Society"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } message.setFrom(new InternetAddress(nick+" <"+from+">")); // Save and generate the final email content message.saveChanges(); // Send email try { Transport.send(message); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Send HTML mail with embedded images*/ public static void sendHtmlWithInnerImageEmail() throws MessagingException { // Create Session instance object Session session = Session.getDefaultInstance(props, new MyAuthenticator()); // Create email content MimeMessage message = new MimeMessage(session); // Mail subject, and specify the encoding format message.setSubject("HTML mail with embedded pictures", "utf-8"); // Sender message.setFrom(new InternetAddress(from)); // Recipient message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); // CC message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]")); // Secret send (not displayed in the list of email recipients) message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]")); // Send time message.setSentDate(new Date()); // Create a MimeMultipart object with MIME subtype "related" MimeMultipart mp = new MimeMultipart("related"); // Create a MimeBodyPart object representing the body and add it to the MimeMultipart object created earlier MimeBodyPart htmlPart = new MimeBodyPart(); mp.addBodyPart(htmlPart); // Create a MimeBodyPart object representing image resources and add it to the MimeMultipart object created earlier MimeBodyPart imagePart = new MimeBodyPart(); mp.addBodyPart(imagePart); // Set the MimeMultipart object to the content of the entire message message.setContent(mp); // Set the embedded image mail body DataSource ds = new FileDataSource(new File("resource/firefoxlogo.png")); DataHandler dh = new DataHandler(ds); imagePart.setDataHandler(dh); imagePart.setContentID("firefoxlogo.png"); // Set the content number to use for other mail body references// Create a MimeMultipart object with MIME subtype "alternative" and serve as the email content of the htmlPart object created earlier MimeMultipart htmlMultipart = new MimeMultipart("alternative"); // Create a MimeBodyPart object representing the html body MimeBodyPart htmlBodypart = new MimeBodyPart(); // where cid=androidlogo.gif is the image inside the reference message, that is, imagePart.setContentID("androidlogo.gif"); method htmlBodypart.setContent("<span style='color:red;'>This is an HTML email with embedded images!!!<img src=/"cid:firefoxlogo.png/" /></span>","text/html;charset=utf-8"); htmlMultipart.addBodyPart(htmlBodypart); htmlPart.setContent(htmlMultipart); // Save and generate the final email content message.saveChanges(); // Send mail Transport.send(message); } /** * Send a complete HTML message with embedded pictures, attachments, multiple recipients (displaying the mailbox name), email priority, and reading receipt*/ public static void sendMultipleEmail() throws Exception { String charset = "utf-8"; // Specify the Chinese encoding format// Create Session instance object Session session = Session.getInstance(props,new MyAuthenticator()); // Create MimeMessage instance object MimeMessage message = new MimeMessage(session); // Set the topic message.setSubject("Use JavaMail to send mixed combination mail test"); // Set sender message.setFrom(new InternetAddress(from,"Sina Test Email",charset)); // Set recipient message.setRecipients(RecipientType.TO, new Address[] { // Parameter 1: Email address, Parameter 2: Name (only the name is displayed in the client receiving, not the email address), Parameter 3: Name Chinese string encoding new InternetAddress("[email protected]", "Zhang San_sohu", charset), new InternetAddress("[email protected]", "Li Si_163", charset), } ); // Set cc message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]","Wang Wu_gmail", charset)); // Set secret message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]", "Zhao Liu_QQ", charset)); // Set send time message.setSentDate(new Date()); // Set the replyer (the default recipient is given when the recipient responds to this email) message.setReplyTo(InternetAddress.parse("/"" + MimeUtility.encodeText("Tian Qi") + "/" <[email protected]>")); // Set priority (1: Emergency 3: Normal 5: Low) message.setHeader("X-Priority", "1"); // Request a reading receipt (the recipient will prompt the sender to reply when reading the email, indicating that the email has been received and has been read) message.setHeader("Disposition-Notification-To", from); // Create a MimeMultipart object with MIME subtype "mixed", indicating that this is a mixed combination type email MimeMultipart mailContent = new MimeMultipart("mixed"); message.setContent(mailContent); // Attachment MimeBodyPart attach1 = new MimeBodyPart(); MimeBodyPart attach2 = new MimeBodyPart(); // Content MimeBodyPart mailBody = new MimeBodyPart(); // Add attachment and content to the mail mailContent.addBodyPart(attach1); mailContent.addBodyPart(attach2); mailContent.addBodyPart(mailBody); // Attachment 1 (Use the jaf framework to generate mail body) DataSource ds1 = new FileDataSource("resource/Earth.bmp"); DataHandler dh1 = new DataHandler(ds1); attach1.setFileName(MimeUtility.encodeText("Earth.bmp")); attach1.setDataHandler(dh1); // Attachment 2 DataSource ds2 = new FileDataSource("resource/How to learn C language well.txt"); DataHandler dh2 = new DataHandler(ds2); attach2.setDataHandler(dh2); attach2.setFileName(MimeUtility.encodeText("How to learn C language well.txt")); // Email body (embedded picture + html text) MimeMultipart body = new MimeMultipart("related"); // Email body is also a combination, and the combination relationship needs to be specified mailBody.setContent(body); // Email body consists of html and pictures MimeBodyPart imgPart = new MimeBodyPart(); MimeBodyPart htmlPart = new MimeBodyPart(); body.addBodyPart(imgPart); body.addBodyPart(htmlPart); // Text image DataSource ds3 = new FileDataSource("resource/firefoxlogo.png"); DataHandler dh3 = new DataHandler(ds3); imgPart.setDataHandler(dh3); imgPart.setContentID("firefoxlogo.png"); // html email content MimeMultipart htmlMultipart = new MimeMultipart("alternative"); htmlPart.setContent(htmlMultipart); MimeBodyPart htmlContent = new MimeBodyPart(); htmlContent.setContent( "<span style='color:red'>This is the email I sent with java mail myself!" + "<img src='cid:firefoxlogo.png' /></span>" , "text/html;charset=gbk"); htmlMultipart.addBodyPart(htmlContent); // Save the message content and modify message.saveChanges(); /*File emml = buildEmlFile(message); sendMailForEml(eml);*/ // Send mail Transport.send(message); } /** * Generate an eml file to the email content* @param message Email content*/ public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException { File file = new File("c://" + MimeUtility.decodeText(message.getSubject())+".eml"); message.writeTo(new FileOutputStream(file)); return file; } /** * Send locally generated email file*/ public static void sendMailForEml(File emml) throws Exception { // Get email session Session session = Session.getInstance(props,new MyAuthenticator()); // Get email content, that is, the eml file generated before it occurs InputStream is = new FileInputStream(eml); MimeMessage message = new MimeMessage(session,is); //Send email Transport.send(message); } /** * Submit authentication information to the mail server*/ static class MyAuthenticator extends Authenticator { private String username = ""; private String password = ""; public MyAuthenticator() { super(); this.password=senduserPwd; this.username=senduserName; } public MyAuthenticator(String username, String password) { super(); this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }}DEMO2 code example:
package com.justin.framework.core.utils.email;import java.util.HashSet;import java.util.Properties;import java.util.Set;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;public class MailManagerUtils { //Send email public static boolean sendMail(Email email) { String subject = email.getSubject(); String content = email.getContent(); String[] recruits = email.getRecievers(); String[] copyright = email.getCopyto(); String attbody = email.getAttbody(); String[] attbodys = email.getAttbodys(); if(recievers == null || collecters.length <=0) { return false; } try { Properties props = new Properties(); props.setProperty("mail.enable", "true"); props.setProperty("mail.protocal", "smtp"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.user", "[email protected]"); props.setProperty("mail.pass", "New***"); props.setProperty("mail.smtp.host","mail.tdb.com"); props.setProperty("mail.smtp.from","[email protected]"); props.setProperty("mail.smtp.fromname","tdbVC"); // Create a program to communicate with the mail server Session mailConnection = Session.getInstance(props, null); Message msg = new MimeMessage(mailConnection); // Set sender and recipient Address sender = new InternetAddress(props.getProperty("mail.smtp.from")); // Multiple recipients msg.setFrom(sender); Set<InternetAddress> toUserSet = new HashSet<InternetAddress>(); // Mailbox validity validation for (int i = 0; i < receivers.length; i++) { if (recievers[i].trim().matches("^//w+([-+.]//w+)*@//w+([-.]//w+)+$")) { toUserSet.add(new InternetAddress(recievers[i].trim())); } } msg.setRecipients(Message.RecipientType.TO, toUserSet.toArray(new InternetAddress[0])); // Set cc if (copyto != null) { Set<InternetAddress> copyToUserSet = new HashSet<InternetAddress>(); // Email validity valid for (int i = 0; i < copyto.length; i++) { if (copyto[i].trim().matches("^//w+([-+.]//w+)*@//w+([-.]//w+)+$")) { copyToUserSet.add(new InternetAddress(copyto[i].trim())); } } // msg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); msg.setRecipients(Message.RecipientType.CC, copyToUserSet.toArray(new InternetAddress[0])); } // Set the email subject msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B")); // Chinese garbled code problem// Set the email content BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=UTF-8"); // Chinese Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); /***************************************/ if (attbody != null) { String[] filePath = attbody.split(";"); for (String filepath : filePath) { //Set the attachment of the letter (use the file on the local machine as the attachment) BodyPart mdp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filepath); DataHandler dh = new DataHandler(fds); mdp.setFileName(MimeUtility.encodeText(fds.getName())); mdp.setDataHandler(dh); multipart.addBodyPart(mdp); } //Put mtp as the content of the message object msg.setContent(multipart); }; if (attbodys != null) { for (String filepath : attbodys) { //Set the attachment of the letter (use the file on the local machine as the attachment) BodyPart mdp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filepath); DataHandler dh = new DataHandler(fds); mdp.setFileName(MimeUtility.encodeText(fds.getName())); mdp.setDataHandler(dh); multipart.addBodyPart(mdp); } //Put mtp as the content of the message object msg.setContent(multipart); } ; /***************************************************/ //Storage the email first msg.saveChanges(); System.out.println("Send email..."); Transport transfer = mailConnection.getTransport(props.getProperty("mail.protocal")); // Mail server name, user name, password trans.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.user"), props.getProperty("mail.pass")); trans.sendMessage(msg, msg.getAllRecipients()); System.out.println("Send mail successfully!"); // Close the channel if (trans.isConnected()) { trans.close(); } return true; } catch (Exception e) { System.err.println("Email send failed!" + e); return false; } finally { } } // The sender, recipient, and the reply holder has garbled Chinese code in the email, res is the address obtained // The default encoding method of http is ISO8859_1 // For sending addresses containing Chinese, use the MimeUtility.decodeTex method// For others, convert the address from ISO8859_1 to gbk encoding public static String getChineseFrom(String res) { String from = res; try { if (from.startsWith("=?GB") || from.startsWith("=?gb") || from.startsWith("=?UTF")) { from = MimeUtility.decodeText(from); } else { from = new String(from.getBytes("ISO8859_1"), "GBK"); } } catch (Exception e) { e.printStackTrace(); } return from; } // Convert to GBK encoding public static String toChinese(String strvalue) { try { if (strvalue == null) return null; else { strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK"); return strvalue; } } catch (Exception e) { return null; } } public static void main(String[] args) { Email email=new Email(); email.setRecievers(new String[]{"[email protected]"}); email.setSubject("TEST test"); email.setContent("TEST test"); sendMail(email); }}Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.