Directly upload source code:
1. Basic information of email (it is set directly to static if it is convenient)
It is best to be a javabean
package com.lgf.Email; import java.util.Date; public class EmailMessage { /** * The email information can be set by yourself. * For convenience, it is directly set to static*/ // Recipient email public static String TO = "[email protected]"; // Sender email public static String FROM = "[email protected]"; public static String FROM_NAME = "xxx"; // Cc public static String CC="[email protected]"; // Secret sending public static String BCC="[email protected]"; // Email type public static String Email_Content = "text/plain"; // Email title public static String Email_Subject = "Test Email With JavaMail"; // Email header public static String Email_Header = "This Is Email Header"; // Content public static String Email_Body = "<a href=/"http://www.baidu.com/">This Is Email Body</a>"; // Server, for example, QQ, can be set to smtp.qq.com public static String Email_Host = "smtp.xxx.com"; // Send time public static Date sendDate = new Date(); // Is it necessary to verify the username and password public static boolean validate = true; } 2. Server verification (that is the username and password when logging in)
package com.lgf.Email; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * Verification of username and password* @author lgf * */ public class MailAuthenticator extends Authenticator{ private String username="xxxxx"; private String password="xxxxx"; public MailAuthenticator() { super(); } /** * Set the authenticated username and password*/ public MailAuthenticator(String userName, String password) { super(); this.username = userName; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(this.username,this.password); } } 3. Set up information and steps before sending emails
package com.lgf.Email; 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.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 com.lgf.SendEmail.MailAuthenticator; public class SendEmail { /** * Send normal mail* @throws Exception */ public void doSendNormalMail() { // Get the system environment Properties prop = new Properties(); Authenticator auth = null; // Determine whether you need to verify if (EmailMessage.validate) { // The mail server authentication username and password auth = new MailAuthenticator(); } // Add necessary information prop.put("mail.smtp.host", EmailMessage.Email_Host); prop.put("mail.smtp.auth", "true"); // Set the conversation and the mail server for communication Session session = Session.getDefaultInstance(prop, auth); // Display the Debug information on the console session.setDebug(true); // Set the mail object Message message = new MimeMessage(session); try { // Set the email subject message.setSubject(EmailMessage.Email_Subject); // Set the email title message.setHeader("Header", EmailMessage.Email_Header); // Set the sending time message.setSentDate(EmailMessage.sendDate); // Set the sender address and name Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME); // Add sender information to the message.setFrom(address); // Set the sender address Address toAddress = new InternetAddress(EmailMessage.TO); // Set the recipient address message.setRecipient(Message.RecipientType.TO, toAddress); // Set multiple recipient addresses// message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); // Set the email format message.setContent("Content", EmailMessage.Email_Content); // Set the email contents must be message.setText(EmailMessage.Email_Body); // Set the message contents after the file format message.setText(EmailMessage.Email_Body); // Save the information added above message.saveChanges(); // Send mail System.out.println("sendNormalEmail() Start sending email..."); Transport.send(message); System.out.println("Send successfully!"); } catch (Exception e) { System.out.println("Error"); e.printStackTrace(); } } /** * Send HTML-formatted mail*/ public void doSendHtmlMail() { // Get the system environment Properties prop = new Properties(); Authenticator auth = null; if (EmailMessage.validate) { // Mail Server Authentication Username and Password auth = new MailAuthenticator(); } // Add necessary information prop.put("mail.smtp.host", EmailMessage.Email_Host); prop.put("mail.smtp.auth", "true"); // Set up conversations and mail servers for communication Session session = Session.getDefaultInstance(prop, auth); // Set mail object Message message = new MimeMessage(session); try { // Set the email subject message.setSubject(EmailMessage.Email_Subject); // Set the email title message.setHeader("Header", EmailMessage.Email_Header); // Set the sending time message.setSentDate(EmailMessage.sendDate); // Set the sender address and name Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME); // Add sender information to message.setFrom(address); // Set the sender address Address toAddress = new InternetAddress(EmailMessage.TO); // Set the recipient address message.setRecipient(Message.RecipientType.TO, toAddress); // Set multiple recipient addresses// message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); // Set the content of the sending message as sending hmml // Set the email format EmailMessage.Email_Content = "text/html; charset=utf-8"; message.setContent(EmailMessage.Email_Body, EmailMessage.Email_Content); // Save the information added above message.saveChanges(); // Send mail System.out.println("doSendHtmlMail() Start sending email..."); Transport.send(message); System.out.println("Send successfully!"); } catch (Exception e) { System.out.println("Error"); e.printStackTrace(); } } /** * Send mail with attachment format*/ public void doSendAttachmentMail() { // Get the system environment Properties prop = new Properties(); Authenticator auth = null; if (EmailMessage.validate) { // Mail Server Authentication Username and Password auth = new MailAuthenticator(); } // Add necessary information prop.put("mail.smtp.host", EmailMessage.Email_Host); prop.put("mail.smtp.auth", "true"); // Set up conversations and mail servers for communication Session session = Session.getDefaultInstance(prop, auth); // Set mail object Message message = new MimeMessage(session); try { // Set the email subject message.setSubject(EmailMessage.Email_Subject); // Set the email title message.setHeader("Header", EmailMessage.Email_Header); // Set the sending time message.setSentDate(EmailMessage.sendDate); // Set the sender address and name Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME); // Add sender information to message.setFrom(address); // Set the sender address Address toAddress = new InternetAddress(EmailMessage.TO); // Set the recipient address message.setRecipient(Message.RecipientType.TO, toAddress); // Set multiple recipient addresses// message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); // Set the content of the sending message below is the sending attachment message.setContent(EmailMessage.Email_Body, EmailMessage.Email_Content); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("bodypart"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); // Set up the uploaded resource DataSource source = new FileDataSource("E://3.doc"); // Add to messageBodyPart.setDataHandler(new DataHandler(source)); // Set the file name, remember the suffix name messageBodyPart.setFileName("test.doc"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); // Save the information added above message.saveChanges(); // Send mail System.out.println("doSendAttachmentMail() Start sending email..."); Transport.send(message); System.out.println("SendSuccessfully!"); } catch (Exception e) { System.out.println("Error"); e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { // new SendEmail().doSendNormalMail(); // new SendEmail().doSendHtmlMail(); new SendEmail().doSendAttachmentMail(); } }The above is the detailed code for Java sending mail javax.mail. I hope it will be helpful to everyone to implement Java email sending.