In actual use, for example, if you shop on Taobao and apply for a refund, you will see a refund email in your email address, or you register an account, apply for verification of email notification, etc. These are all email sending. Here will introduce the case of abnormal email transmission by the system.
Preparation:
eclipse4.5 64 bit
jdk1.7 64 bit
The required jar to send mail:
fastjson-1.1.24.jar, javax.mail-1.5.6.jar
Class Developer:
Enumeration type, sender's name and email address
package mail; /** * @class:Developer *@descript: Enumeration type, sender's name and email address*@date: October 26, 2016 at 8:07:50 pm *@author sanghaiqin *@version:V1.0 */ public enum Developer { zhoujing("Zhou Jing","[email protected]"), peiyuxiang("Pei Yuxiang","[email protected]"), yipeng("Ypeng","[email protected]"), liuan("Liu An","[email protected]"), chenyuhao("Chen Yuhao","[email protected]"), wangdong("Wang Dong","[email protected]"), sanghaiqin("Sang Haiqin","[email protected]"); //Sender's name private String name; //Sender email private String mail; private Developer() { } private Developer(String name, String mail) { this.name = name; this.mail = mail; } /** * @descript: Pass the sender's name to get the sender's email* @param name Sender's name* @return */ public static String getMail(String name) { for (Developer c : Developer.values()) { if (c.getName().equals(name)) { return c.mail; } } return null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } } Class ExceptionInfo: Sender information
package mail; /** * @class:ExceptionInfo *@descript:Sender information*@date:October 26, 2016 at 8:11:27 pm *@author sanghaiqin *@version:V1.0 */ public class ExceptionInfo { //Sender name private String developer; //Sender method private String method; //Sender url private String url; //Sender catches exception information private Exception e; /** * @param developer Sender name* @param method Sender method* @param url Sender url * @param e Sender catches exception information*/ public ExceptionInfo(String developer, String method, String url, Exception e) { super(); this.developer = developer; this.method = method; this.url = url; this.e = e; } public String getDeveloper() { return developer; } public void setDeveloper(String developer) { this.developer = developer; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Exception getE() { return e; } public void setE(Exception e) { this.e = e; } } MailSenderInfo: Send email information
package mail; import java.util.Properties; /** * @class:MailSenderInfo *@descript:Send email information*@date:October 26, 2016 at 8:14:22 pm *@author sanghaiqin *@version:V1.0 */ public class MailSenderInfo { //The IP private String mailServerHost of the server sending the mail; //The port of the server sending the mail is 25 private String mailServerPort = "25"; // The address of the sender of the mail private String fromAddress; // The address of the mail recipient private String toAddress; // Log in to the mail sending server's username private String username; // Log in to the mail sending server's password private String password; // Do you need authentication private boolean validate = false; // Email subject private String subject; // Text content of the mail private String content; // File name of the mail attachment private String[] attachFileNames; public MailSenderInfo() { super(); } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String textContent) { this.content = textContent; } /** * @descript: Get email session property* @return */ public Properties getProperties() { PropertyUtil propertyUtil = new PropertyUtil(); Properties properties =propertyUtil.readProperties(); return properties; } } Class MyAuthenticator: User Authenticator
package mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * @class:MyAuthenticator *@descript:User verification*@date:October 26, 2016 at 8:57:45 pm *@author sanghaiqin *@version:V1.0 */ public class MyAuthenticator extends Authenticator { //Username String username = null; //Password String password = null; public MyAuthenticator() { } public MyAuthenticator(String username, String password) { this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } Class PropertyUtil: Obtain properties file tool class
package mail; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @class:PropertyUtil *@descript: Obtain properties file tool class*@date: October 26, 2016 at 8:20:10 pm *@author sanghaiqin *@version:V1.0 */ public class PropertyUtil { /** * @descript:Loading resource file* @param resources resource file* @return * @throws FileNotFoundException */ private Properties loadProperties(String resources) { InputStream inputstream = null; Properties properties = new Properties(); // Use InputStream to get a resource file try { inputstream = new FileInputStream(resources); // Load the configuration file properties.load(inputstream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if(inputstream!=null){ try { inputstream.close(); } catch (IOException e) { e.printStackTrace(); } } return properties; } /** * @descript: Read property file* @return * @throws FileNotFoundException */ public Properties readProperties(){ String resources = PropertyUtil.class.getClassLoader().getResource("prop.properties").getPath(); Properties properties = loadProperties(resources); return properties; } /** * @descript: Test* @param args */ public static void main(String[] args) { PropertyUtil p=new PropertyUtil(); Properties pro=p.readProperties(); String mailSenderUsername=(String) pro.get("mail.sender.username"); System.out.println("Mail Sender Username: "+mailSenderUsername);//[email protected] String path = PropertyUtil.class.getClassLoader().getResource("prop.properties").getPath(); System.out.println(path);// /G:/Workspaces4.4/test/bin/prop.properties } } Resource file pro.properties:
#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ #Sender's email address [email protected]
JavaMail class: Send mailbox
package mail; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; 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. javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; 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; /** * @class:JavaMail *@descript:Jar package required to send information mailbox*: *fastjson-1.1.24.jar *javax.mail-1.5.6.jar *@date: October 26, 2016 at 8:13:05 pm *@author sanghaiqin *@version:V1.0 */ public class JavaMail { public static void sendExceptionMail(ExceptionInfo info){ try { //Get the sender's email through the sender String mail = Developer.getMail(info.getDeveloper()); if(mail!=null){ MailSenderInfo mailInfo = new MailSenderInfo(); //Set the text content of the email mailInfo.setContent("Responsible: "+info.getDeveloper()+"==>Server ip:"+InetAddress.getLocalHost().getHostAddress()+"==>Method name: "+info.getMethod()+"==>Address: "+info.getUrl()+"==>Exception information: "+getEmessage(info.getE())); //Set the address of the email recipient mailInfo.setToAddress(mail); //Email subject mailInfo.setSubject("Yika Aitu Exception Notification"); //Send email sendTextMail(mailInfo); } } catch (UnknownHostException e) { e.printStackTrace(); } } /** * @descript: Send email in text format* @param: mailInfo Information of the email to be sent* @return: Send true after successful sending; return false after failure */ public static boolean sendTextMail(MailSenderInfo mailInfo) { // Determine whether identity authentication is required MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); try { if ("true".trim().equals(pro.getProperty("mail.smtp.auth"))) { // If authentication is required, create a password authenticator authenticator = new MyAuthenticator(pro.getProperty("mail.sender.username"),pro.getProperty("mail.sender.password")); } // Construct a session to send mail based on the mail session properties and password authenticator Session sendMailSession = Session.getDefaultInstance(pro, authenticator); // Create a mail message based on the session Message mailMessage = new MimeMessage(sendMailSession); // Create the sender of the mail message Address from = new InternetAddress(pro.getProperty("mail.sender.address")); // Set the sender of the mail message mailMessage.setFrom(from); // Create the recipient address of the mail message and set it to the mail message Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO attribute indicates that the type of the recipient is TO mailMessage.setRecipient(Message.RecipientType.TO, to); // Set the subject of the mail message mailMessage.setSubject(mailInfo.getSubject()); // Set the time for sending the mail message mailMessage.setSentDate(new Date()); // Set the main content of the mail message mailMessage.setText(mailInfo.getContent()); // Send mail Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * @descript: Send mail in HTML format * @param mailInfo: Information of the mail to be sent * @param attachment: attachment content* @return: true when sent successfully; false when failed */ public static boolean sendHtmlMail(MailSenderInfo mailInfo, String[] attachment) { // Determine whether identity authentication is required MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); try { // If identity authentication is required, create a password authenticator if ("true".trim().equals(pro.getProperty("mail.smtp.auth"))) { // If identity authentication is required, create a password authenticator = new MyAuthenticator(pro.getProperty("mail.sender.username"),pro.getProperty("mail.sender.password")); } // Construct a session to send mail based on the mail session properties and password authenticator. Session sendMailSession = Session.getDefaultInstance(pro, authenticator); // Create a mail message based on the session Message mailMessage = new MimeMessage(sendMailSession); // Create a mail sender address Address from = new InternetAddress(pro.getProperty("mail.sender.address")); // Set the sender of the mail message mailMessage.setFrom(from); // Create the recipient address of the mail message and set it to the mail message Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO attribute indicates that the type of the recipient is TO mailMessage.setRecipient(Message.RecipientType.TO, to); // Set the subject of the mail message mailMessage.setSubject(mailInfo.getSubject()); // Set the time for sending mail messages mailMessage.setSentDate(new Date()); // MiniMultipart class is a container class that contains an object of MimeBodyPart type Multipart mainPart = new MimeMultipart(); // Create a MimeBodyPart containing HTML content BodyPart html = new MimeBodyPart(); // Set HTML content html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); // Add HTML content MimeBodyPart mainPart.addBodyPart(html); // Add attachment content if (attachment != null) { for (String filePath : attachment) { MimeBodyPart filePart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); filePart.setDataHandler(new DataHandler(source)); try { // The method circulating online to solve garbled filenames is actually very convenient to use MimeUtility.encodeWord to solve filePart.setFileName(MimeUtility.encodeWord(source.getName())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mainPart.addBodyPart(filePart); } } // Set the MiniMultipart object to the mail content mailMessage.setContent(mainPart); // Keep the content mailMessage.saveChanges(); // Send mailTransport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * @descript: Get exception information about the sender method* Use strings as the character input and output streams of physical nodes, that is, the usage of StringReader and StringWriter* PrintWriter(Writer out, boolean autoFlush) Create a new PrintWriter with automatic row refresh, true means it can refresh automatically* @param e Exception information* @return */ private static String getEmessage(Exception e){ //StringWriter output exception information StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); pw.flush(); sw.flush(); return sw.toString(); } /** * @descript:Test* @param args */ public static void main(String[] args) { //Test 1: Send email in text format try { String s=""; s.substring(2); } catch (Exception e) { e.printStackTrace(); System.out.println(getEmessage(e)); sendExceptionMail(new ExceptionInfo( Developer.sanghaiqin.getName(),"get()", "123",e)); } //Test 2: Send email in html format MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setToAddress("[email protected]"); // Set the recipient's email address mailInfo.setSubject("Title"); mailInfo.setContent("Content<h1>www.baidu.com</h1>"); String[] files = {"G:/upload/image/2016/10/28/1477372845440.jpg","G:/upload/image/2016/10/28/1477372845660.jpg"}; JavaMail.sendHtmlMail(mailInfo,files); // Send html format System.out.println("Send successfully"); } }Test screenshot:
Test 1: Send emails in text format:
Test 2: Send emails in html format:
Project structure screenshot:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.