Send a simple email based on SMTP
First, an authenticator is needed:
package No001_SMTP-based text mail; import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;public class SimpleAuthenticator extends Authenticator {private String username;private String password;public SimpleAuthenticator(String username, String password) {super();this.username = username;this.password = password;}protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}} Then, write a simple email sending program:
package No001_ SMTP-based text mail; import java.util.Properties;import javax.mail.Message;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.Address;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class SMTPSimpleMail {public static void main(String[] args) throws AddressException, MessagingException {/* Required information*/String SMTP_MAIL_HOST = "smtp.163.com"; // This email server address, go to the email to query String EMAIL_USERNAME = "[email protected]";String EMAIL_PASSWORD = "mypassword";String TO_EMAIL_ADDRESS = "[email protected]";/* Server information*/Properties props = new Properties();props.put("mail.smtp.host", SMTP_MAIL_HOST);props.put("mail.smtp.auth", "true");/* Create Session */Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));/* Email message*/MimeMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(EMAIL_USERNAME));message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS));message.setSubject("how to use java mail to send email.(Title)(001)");message.setText("how to use java mail to send email.(Content)");// Send Transport.send(message);System.out.println("It's not particularly unlucky, you can check the email. ");}} What should I do if I send various recipients, ccs, secret ccs
Authenticator is used, omitted.
In fact, it is to set up, add multiple recipients, cc senders, and secret cc senders:
package No002_What should I do if various senders and recipients send cc to the cc; import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.Message;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class SendMailWithMultiPeople {public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {/* Required information*/String SMTP_MAIL_HOST = "smtp.163.com"; // This mail server address, go to the email to which it belongs to search String EMAIL_USERNAME = "[email protected]";String EMAIL_PASSWORD = "mypassword";String TO_EMAIL_ADDRESS_1 = "[email protected]";String CC_EMAIL_ADDRESS_1 = "[email protected]";String BCC_EMAIL_ADDRESS_1 = "[email protected]";/* Server Information*/Properties props = new Properties();props.put("mail.smtp.host", SMTP_MAIL_HOST);props.put("mail.smtp.auth", "true");/* Create Session */Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));/* Sender*/Address[] senderArray = new Address[1];senderArray[0] = new InternetAddress("[email protected]", "Nick Huang");/* Email message*/MimeMessage message = new MimeMessage(session);message.addFrom(senderArray);message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(CC_EMAIL_ADDRESS_1)); message.addRecipient(Message.RecipientType.CC, new InternetAddress(CC_EMAIL_ADDRESS_1)); message.addRecipient(Message.RecipientType.CC, new InternetAddress(TO_EMAIL_ADDRESS_1)); message.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC_EMAIL_ADDRESS_1)); message.setSubject("I am a mail learning Java Mail"); message.setText("I am a mail learning Java Mail, please give me a good start. ");// Send Transport.send(message);System.out.println("Not particularly unlucky, you can check the email.");}} What to do if you send attachments
Authenticator is used, omitted.
Send attachment demo:
package No003_What to do if you send attachments; import java.io.File;import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Address;import 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.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class SendMailWithAttachment {public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {/* Required information*/String SMTP_MAIL_HOST = "smtp.163.com"; // This mail server address, go to the email to query String EMAIL_USERNAME = "[email protected]";String EMAIL_PASSWORD = "password";String TO_EMAIL_ADDRESS_1 = "[email protected]";/* Server information*/Properties props = new Properties();props.put("mail.smtp.host", SMTP_MAIL_HOST);props.put("mail.smtp.auth", "true");/* Create Session */Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));/* Sender*/Address[] senderArray = new Address[1];senderArray[0] = new InternetAddress(EMAIL_USERNAME);/* Email message*/MimeMessage message = new MimeMessage(session);message.addFrom(senderArray);message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));message.setSubject("I am an email learning Java Mail");BodyPart bodyPart = new MimeBodyPart();bodyPart.setText("This is the content of an email learning Java Mail, please give it a lot of money. ");/* Attachment*/BodyPart attachmentPart1 = new MimeBodyPart();DataSource source = new FileDataSource(new File("D:/File 1.txt"));attachmentPart1.setDataHandler(new DataHandler(source));attachmentPart1.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode("File 1.txt".getBytes()) + "?=");BodyPart attachmentPart2 = new MimeBodyPart();source = new FileDataSource(new File("D:/File 2.txt"));attachmentPart2.setDataHandler(new DataHandler(source));attachmentPart2.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode("File 2.txt".getBytes()) + "?=");Multipart multipart = new MimeMultipart();multipart.addBodyPart(bodyPart);multipart.addBodyPart(attachmentPart1);multipart.addBodyPart(attachmentPart2);message.setContent(multipart);// Send Transport.send(message);System.out.println("Not particularly unlucky, you can check the email.");}} Also, send HTML mail
Authenticator is used, omitted.
In fact, it is to tell the recipient client to parse and render with HTML:
package No004_Send HTML mail; import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class HowToSendHTMLMail {public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {/* Required information*/String SMTP_MAIL_HOST = "smtp.163.com"; // This mail server address, go to the email to which you belong to search String EMAIL_USERNAME = "[email protected]";String EMAIL_PASSWORD = "password";String TO_EMAIL_ADDRESS_1 = "[email protected]";/* Server information*/Properties props = new Properties();props.put("mail.smtp.host", SMTP_MAIL_HOST);props.put("mail.smtp.auth", "true");/* Create Session */Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(EMAIL_USERNAME, EMAIL_PASSWORD));/* Sender*/Address[] senderArray = new Address[1];senderArray[0] = new InternetAddress(EMAIL_USERNAME);/* Email message*/MimeMessage message = new MimeMessage(session);message.addFrom(senderArray);message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_EMAIL_ADDRESS_1));message.setSubject("How to send HTML messages");/* Text*/MimeBodyPart bodyPart = new MimeBodyPart();bodyPart.setContent("<h1>loving you...</h2>", "text/html;charset=gb2312");/* Encapsulate information of various parts of the email*/Multipart multipart = new MimeMultipart();multipart.addBodyPart(bodyPart);message.setContent(multipart);// Send Transport.send(message);System.out.println("It's not particularly unlucky, you can check the email. ");}} Or, come with a tool class?
Authenticator is certain, used, and omitted.
Since there are many and complicated properties that need to be set, name it with a simple and easy-to-use attribute for your own, so use a configuration class
package No005_Get a tool class; import java.io.File;import java.util.ArrayList;import java.util.List;public class MailSenderConfig {private String SMTPMailHost; // Mail server address that supports SMTP protocol/* Used to log in to the mail server*/private String username;private String password;private String subject; // Title private String content; // Content private String fromMail; // Show emails sent from this mailbox private List<String> toMails; // Recipient private List<String> ccMails; // cc private List<String> bccMails; // Secret cc private List<File> attachments; // Attachment public MailSenderConfig(String sMTPMailHost, String subject,String content, String fromMail) {super();SMTPMailHost = sMTPMailHost; this.subject = subject; this.content = content; this.fromMail = fromMail;}public String getSMTPMailHost() {return SMTPMailHost;}public void setSMTPMailHost(String sMTPMailHost) {SMTPMailHost = sMTPMailHost;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getFromMail() {return fromMail;}public void setFromMail(String fromMail) {this.fromMail = fromMail;}public List<String> getToMails() {return toMails;}public void setToMails(List<String> toMails) {this.toMails = toMails;}public List<String> getCcMails() {return ccMails;}public void setCcMails(List<String> ccMails) {this.ccMails = ccMails;}public List<String> getBccMails() {return bccMails;}public void setBccMails(List<String> bccMails) {this.bccMails = bccMails;}public List<File> getAttachments() {return attachments;}public void setAttachments(List<File> attachments) {this.attachments = attachments;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public void addToMail (String mail) {if (this.toMails == null) {this.toMails = new ArrayList<String>();}this.toMails.add(mail);}public void addCcMail (String mail) {if (this.ccMails == null) {this.ccMails = new ArrayList<String>();}this.ccMails.add(mail);}public void addBccMail (String mail) {if (this.bccMails == null) {this.bccMails = new ArrayList<String>();}this.bccMails.add(mail);}public void addAttachment (File f) {if (this.attachments == null) {this.attachments = new ArrayList<File>();}this.attachments.add(f);}} Finally, there is the tool class part, which is mainly responsible for several things: performing some initialization actions according to Java Mail rules, translating custom attribute configuration classes, setting them with Java Mail rules, and sending emails.
Also, it should be mentioned that because the properties provided by the tool class are limited, more cases may not meet the needs, so MimeMessage is exposed. If the needs are not met, developers can process and configure it themselves, while other parts can still use the tool class.
package No005_Get a tool class; import java.io.File;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Address;import 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 No002_What should I do if various senders and recipients send cc.SimpleAuthenticator;public class MailSender {private MailSenderConfig c;private MimeMessage message;public MailSender(MailSenderConfig config) throws Exception {super();this.c = config;this.setConfig();}/*** Initialization* @return*/private Session initSession() {Properties props = new Properties();if (c.getSMTPMailHost() != null && c.getSMTPMailHost().length() > 0) {props.put("mail.smtp.host", c.getSMTPMailHost());}if (c.getUsername() != null && c.getUsername().length() > 0 && c.getPassword() != null && c.getPassword().length() > 0) {props.put("mail.smtp.auth", "true");return Session.getDefaultInstance(props, new SimpleAuthenticator(c.getUsername(), c.getPassword()));} else {props.put("mail.smtp.auth", "false");return Session.getDefaultInstance(props);}}/*** Set Java Mail properties* @throws Exception*/private void setConfig() throws Exception {this.configValid();Session s = this.initSession();message = new MimeMessage(s);/* Sender*/Address[] fromMailArray = new Address[1];fromMailArray[0] = new InternetAddress(c.getFromMail());message.addFrom(fromMailArray);if (c.getToMails() != null && c.getToMails().size() > 0) {for (String mail: c.getToMails()) {message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));}}if (c.getCcMails() != null && c.getCcMails().size() > 0) {for (String mail : c.getCcMails()) {message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));}}if (c.getToMails() != null && c.getToMails().size() > 0) {for (String mail : c.getToMails()) {message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail));}}// Mail title message.setSubject(c.getSubject());/* Text*/MimeBodyPart bodyPart = new MimeBodyPart();bodyPart.setContent(c.getContent(), "text/html;charset=gb2312");/* Encapsulate information of each part of the email*/Multipart multipart = new MimeMultipart();multipart.addBodyPart(bodyPart);message.setContent(multipart);BodyPart attachmentPart = null;DataSource ds = null;if (c.getAttachments() != null && c.getAttachments().size() > 0) {for (File f : c.getAttachments()) {attachmentPart = new MimeBodyPart();ds = new FileDataSource(f);attachmentPart.setDataHandler(new DataHandler(ds));attachmentPart.setFileName("=?GBK?B?" + new sun.misc.BASE64Encoder().encode(f.getName().getBytes()) + "?=");multipart.addBodyPart(attachmentPart);}}message.setContent(multipart);}/*** Configuration Verification* @throws Exception*/private void configValid() throws Exception {if (c == null) {throw new Exception("Configuration object is empty");}if (c.getSMTPMailHost() == null || c.getSMTPMailHost().length() == 0) {throw new Exception("SMTP server is empty");}if (c.getFromMail() == null && c.getFromMail().length() == 0) {throw new Exception("Sender mail is empty");}if (c.getToMails() == null || c.getToMails().size() < 1) {throw new Exception("Recipient mail is empty");}if (c.getSubject() == null || c.getSubject().length() == 0) {throw new Exception("Email title is empty");}if (c.getContent() == null || c.getContent().length() == 0) {throw new Exception("Email content is empty");}}/*** Send email* @throws MessagingException*/public void send() throws MessagingException {Transport.send(message);}/*** Set MimeMessage to expose this object so that developers can set personalized properties by themselves* @return*/public MimeMessage getMessage() {return message;}/*** Set MimeMessage to expose this object so that developers can set personalized properties by themselves* @return*/public void setMessage(MimeMessage message) {this.message = message;}} Provide a simple test class package No005_to a tool class; import java.io.File;import javax.mail.internet.MimeMessage;public class TestCall {public static void main(String[] args) throws Exception {/* Required information*/String SMTP_MAIL_HOST = "smtp.163.com"; // This mail server address, go to the email to which you belong to, and check String EMAIL_USERNAME = "[email protected]";String EMAIL_PASSWORD = "password";String TO_EMAIL_ADDRESS_1 = "[email protected]";String TO_EMAIL_ADDRESS_2 = "[email protected]";/* Usage 1, normal use*//*MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, "this is test mail for test java mail framework 3.", "this is content 3.", EMAIL_USERNAME);c.setUsername(EMAIL_USERNAME);c.setPassword(EMAIL_PASSWORD);c.addToMail(TO_EMAIL_ADDRESS_1);c.addToMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_1);c.addAttachment(new File("d:/1.txt"));MailSender ms = new MailSender(c);ms.send();System.out.println("sent...");*//* Usage 2. In more cases, the settings made by the tool class do not meet the needs, so MimeMessage is exposed and */MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, "this is test mail for test java mail framework 4.", "this is content 4.", EMAIL_USERNAME);c.setUsername(EMAIL_USERNAME);c.setPassword(EMAIL_PASSWORD);c.addToMail(TO_EMAIL_ADDRESS_1);c.addToMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_1);c.addAttachment(new File("d:/1.txt"));MailSender ms = new MailSender(c);MimeMessage message = ms.getMessage();message.setContent("this is the replaced content by MimeMessage 4.", "text/html;charset=utf-8");ms.setMessage(message);ms.send();System.out.println("sent...");}} Upgrade the tool class
In actual use, I found that when sending emails in batches, the support of the tool class is not good. For example, sending 100 emails, according to the logic of the above tool class, a connection is established for every email sent. So, isn’t 100 emails 100 times? This is a serious waste.
So, some upgrades are made to this point:
Authenticator is certain, used, and omitted.
Configuration class
import java.util.ArrayList;import java.util.List;public class MailSenderConfig {private String SMTPMailHost; // Mail server address that supports SMTP protocol/* Used to log in to the mail server*/private String username;private String password;private String subject; // Title private String content; // Content private String fromMail; // Show emails sent from this mailbox private List<String> toMails; // Recipient private List<String> ccMails; // ccp private List<String> bccMails; // Secret ccp private List<Attachment> attachments; // Attachment private String contentType = "text/html;charset=utf-8";/*** Constructor* @param sMTPMailHost SMTP server* @param subject Title* @param content content (sent in the form of "text/html;charset=utf-8" by default)* @param fromMail Sender address*/public MailSenderConfig(String sMTPMailHost, String subject,String content, String fromMail) {super();SMTPMailHost = sMTPMailHost; this.subject = subject; this.content = content; this.fromMail = fromMail;}/*** Constructor* @param sMTPMailHost SMTP server* @param username Mail server username @param password Mail server password* @param subject Title* @param content content (sent in the form of "text/html;charset=utf-8" by default)* @param fromMail Sender address*/public MailSenderConfig(String sMTPMailHost, String username,String password, String subject, String content, String fromMail) {super();SMTPMailHost = sMTPMailHost; this.username = username; this.password = password; this.subject = subject; this.content = content; this.fromMail = fromMail;}public void addToMail (String mail) {if (this.toMails == null) {this.toMails = new ArrayList<String>();}this.toMails.add(mail);}public void addCcMail (String mail) {if (this.ccMails == null) {this.ccMails = new ArrayList<String>();}this.ccMails.add(mail);}public void addBccMail (String mail) {if (this.bccMails == null) {this.bccMails = new ArrayList<String>();}this.bccMails.add(mail);}public void addAttachment (Attachment a) {if (this.attachments == null) {this.attachments = new ArrayList<Attachment>();}this.attachments.add(a);}/** Getter and Setter*/public String getSMTPMailHost() {return SMTPMailHost;}public void setSMTPMailHost(String sMTPMailHost) {SMTPMailHost = sMTPMailHost;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getFromMail() {return fromMail;}public void setFromMail(String fromMail) {this.fromMail = fromMail;}public List<String> getToMails() {return toMails;}public void setToMails(List<String> toMails) {this.toMails = toMails;}public List<String> getCcMails() {return ccMails;}public void setCcMails(List<String> ccMails) {this.ccMails = ccMails;}public List<String> getBccMails() {return bccMails;}public void setBccMails(List<String> bccMails) {this.bccMails = bccMails;}public List<Attachment> getAttachments() {return attachments;}public void setAttachments(List<Attachment> attachments) {this.attachments = attachments;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getContentType() {return contentType;}public void setContentType(String contentType) {this.contentType = contentType;}} Attachment entity class import java.io.File;/*** Email attachment entity class*/public class Attachment {private File file;private String filename;public File getFile() {return file;}public void setFile(File file) {this.file = file;}public String getFilename() {if (filename == null || filename.trim().length() == 0) {return file.getName();}return filename;}public void setFilename(String filename) {this.filename = filename;}public Attachment(File file, String filename) {super();this.file = file;this.filename = filename;}public Attachment(File file) {super();this.file = file;}} abstract sending class import java.util.Properties;import javax.mail.Session;public abstract class AbstractSessionMailSender {protected Session session;/*** Initialize Session* @return*/public static Session initSession(MailSenderConfig c) {Properties props = new Properties();if (c.getSMTPMailHost() != null && c.getSMTPMailHost().length() > 0) {props.put("mail.smtp.host", c.getSMTPMailHost());}if (c.getUsername() != null && c.getUsername().length() > 0 && c.getPassword() != null && c.getPassword().length() > 0) {props.put("mail.smtp.auth", "true");return Session.getDefaultInstance(props, new SimpleAuthenticator(c.getUsername(), c.getPassword()));} else {props.put("mail.smtp.auth", "false");return Session.getDefaultInstance(props);}}/*** Expose Getter and Setter to provide the setability of Session to support batch sending of emails/send multiple emails, Session can be cached. @return*/public Session getSession() {return session;}public void setSession(Session session) {this.session = session;}} Send class
import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Address;import 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;public class MailSender extends AbstractSessionMailSender {private MailSenderConfig c;private MimeMessage message;public MailSender(MailSenderConfig config) throws Exception {super();this.c = config; this.setConfig();}public MailSender(MailSenderConfig config, Session session) throws Exception {super(); this.c = config; this.setConfig(); super.setSession(session);}/*** Send email* @throws MessagingException*/public void send() throws MessagingException {Transport.send(message);}/*** Get MimeMessage and expose this object to facilitate the developer to set personalized properties (methods that are not supported by this tool class can be set by the developer themselves, and after setting them up)* @return*/public MimeMessage getMessage() {return message;}/*** Set MimeMessage to expose this object to facilitate developers to set personalized properties (methods that are not supported by this tool class can be set by developers themselves, and after setting them up) * @return*/public void setMessage(MimeMessage message) {this.message = message;}/*** Set Java Mail attributes* @throws Exception*/private void setConfig() throws Exception {this.configValid();if (session == null) {session = initSession(c);}message = new MimeMessage(session);/* Sender*/Address[] fromMailArray = new Address[1];fromMailArray[0] = new InternetAddress(c.getFromMail());message.addFrom(fromMailArray);if (c.getToMails() != null && c.getToMails().size() > 0) {for (String mail: c.getToMails()) {message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));}}if (c.getCcMails() != null && c.getCcMails().size() > 0) {for (String mail: c.getCcMails()) {message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));}}if (c.getToMails() != null && c.getToMails().size() > 0) {for (String mail: c.getToMails()) {message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail));}}// Email title message.setSubject(c.getSubject());/* Text*/MimeBodyPart bodyPart = new MimeBodyPart();bodyPart.setContent(c.getContent(), c.getContentType());/* Encapsulate information of each part of the email*/Multipart multipart = new MimeMultipart();multipart.addBodyPart(bodyPart);message.setContent(multipart);/* Attachment*/BodyPart attachmentPart = null;DataSource ds = null;if (c.getAttachments() != null && c.getAttachments().size() > 0) {for (Attachment a : c.getAttachments()) {attachmentPart = new MimeBodyPart();ds = new FileDataSource(a.getFile());attachmentPart.setDataHandler(new DataHandler(ds));attachmentPart.setFileName(MimeUtility.encodeText(a.getFilename()));multipart.addBodyPart(attachmentPart);}}message.setContent(multipart);}/*** Configuration Verification* @throws Exception*/private void configValid() throws Exception {if (c == null) {throw new Exception("Configuration object is empty");}if (c.getSMTPMailHost() == null || c.getSMTPMailHost().length() == 0) {throw new Exception("SMTP server is empty");}if (c.getFromMail() == null && c.getFromMail().length() == 0) {throw new Exception("Sender mail is empty");}if (c.getToMails() == null || c.getToMails().size() < 1) {throw new Exception("Recipient mail is empty");}if (c.getSubject() == null || c.getSubject().length() == 0) {throw new Exception("Email title is empty");}if (c.getContent() == null || c.getContent().length() == 0) {throw new Exception("Email content is empty");}}} A Junit test class import java.io.File;import javax.mail.Session;import javax.mail.internet.MimeMessage;import org.junit.Test;public class ReadMe {/* Required information*/String SMTP_MAIL_HOST = "smtp.163.com"; // This mail server address, go to the description page of the mail server to which you belong to, and check String EMAIL_USERNAME = "[email protected]";String EMAIL_PASSWORD = "password";String TO_EMAIL_ADDRESS_1 = "[email protected]";/* Optional information*/String TO_EMAIL_ADDRESS_2 = "[email protected]";@Testpublic void case1() throws Exception {/* Usage situation 1, normal use*/MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, "this is a mail for test java mail framework in case1.", "this is content.", EMAIL_USERNAME);c.setUsername(EMAIL_USERNAME);c.setPassword(EMAIL_PASSWORD);c.addToMail(TO_EMAIL_ADDRESS_1);c.addToMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_1);c.addAttachment(new Attachment(new File("d:/1.txt")));MailSender ms = new MailSender(c);ms.send();System.out.println("sent...");}@Testpublic void case2() throws Exception {/* Usage 2. In more cases, the settings made by the tool class do not meet the needs, so MimeMessage is exposed to facilitate developers to set personalized properties*/MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, "this is a mail for test java mail framework in case2.", "this is content.", EMAIL_USERNAME);c.setUsername(EMAIL_USERNAME);c.setPassword(EMAIL_PASSWORD);c.addToMail(TO_EMAIL_ADDRESS_1);c.addToMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_1);c.addAttachment(new Attachment(new File("d:/1.txt")));MailSender ms = new MailSender(c);MimeMessage message = ms.getMessage();message.setContent("this is the replaced content by MimeMessage in case2.", "text/html;charset=utf-8");ms.setMessage(message);ms.send();System.out.println("sent...");}@Testpublic void case3() throws Exception {/* Usage situation 3, send emails multiple times, and the Session can be cached so that the Session will be shared by multiple times to reduce the repeated creation of Session* At the same time, you need to pay attention to the timeliness of the cached Session*/MailSenderConfig c = new MailSenderConfig(SMTP_MAIL_HOST, "this is the first mail for test java mail framework to share session in case3.", "this is content.", EMAIL_USERNAME);c.setUsername(EMAIL_USERNAME);c.setPassword(EMAIL_PASSWORD);c.addToMail(TO_EMAIL_ADDRESS_1);c.addToMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_2);c.addCcMail(TO_EMAIL_ADDRESS_1);c.addAttachment(new Attachment(new File("d:/1.txt")));Session session = MailSender.initSession(c);MailSender ms = new MailSender(c, session);ms.send();c.setSubject("this is the second mail for test java mail framework to share session in case3.");c.setContent("this is content 2.");ms = new MailSender(c, session);ms.send();System.out.println("sent...");}} Summarize
At present, there are so many needs I have. If I encounter other common needs in the future and have time, I will add them further.
The above is a summary of the common needs of sending emails in Java introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!