Downloading and uploading attachments, sending text messages and sending emails are all very commonly used functions in the program. I recorded the upload and download of files and sent text messages. Since I was busy recently, I didn’t have time to do the email sending function. Now I have finally successfully sent emails to the qq email with 163 mailbox. The following are the relevant codes. For details, please refer to the comments in the code:
package test; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; 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 com.sun.mail.util.MailSSLSocketFactory; ///*/ * // * @author tuzongxun123 // * @Description Mail Send Test Class// */ public class sendMailTest { public static void main(String[] args) throws Exception { // Configuration information Properties pro = new Properties(); pro.put("mail.smtp.host", "smtp.163.com"); pro.put("mail.smtp.auth", "true"); // SSL encryption MailSSLSocketFactory sf = null; sf = new MailSSLSocketFactory(); // Set trust all hosts sf.setTrustAllHosts(true); pro.put("mail.smtp.ssl.enable", "true"); pro.put("mail.smtp.ssl.socketFactory", sf); // Construct a session for sending emails based on the session properties of the email. It should be noted here that the user name cannot be suffixed, otherwise it will not be the user name. // It should also be noted that the password here is not the login password of the mailbox normally, but another special authorization code generated by the client MailAuthenticator authorizer = new MailAuthenticator("tuzongxun123", "client authorization code"); Session session = Session.getInstance(pro, authorizer); // Construct email information based on Session Message message = new MimeMessage(session); // Create email sender address Address from = new InternetAddress("[email protected]"); // Set the sender of the email message.setFrom(from); // Verify the recipient's email address List<String> toAddressList = new ArrayList<>(); toAddressList.add("[email protected]"); StringBuffer buffer = new StringBuffer(); if (!toAddressList.isEmpty()) { String regEx = "^([a-z0-9A-Z]+[-|//.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?//.)+[a-zA-Z]{2,}$"; Pattern p = Pattern.compile(regEx); for (int i = 0; i < toAddressList.size(); i++) { Matcher match = p.matcher(toAddressList.get(i)); if (match.matches()) { buffer.append(toAddressList.get(i)); if (i < toAddressList.size() - 1) { buffer.append(","); } } } } } String toAddress = buffer.toString(); if (!toAddress.isEmpty()) { // Create the recipient address of the message Address[] to = InternetAddress.parse(toAddress); // Set the email recipient address message.setRecipients(Message.RecipientType.TO, to); // Email subject// message.setSubject("java mail test"); message.setSubject("Why is wrong"); // Email container MimeMultipart mimeMultiPart = new MimeMultipart(); // Set HTML BodyPart bodyPart = new MimeBodyPart(); // Mail content// String htmlText = "java email test 111"; String htmlText = "Why is it wrong"; bodyPart.setContent(htmlText, "text/html;charset=utf-8"); mimeMultiPart.addBodyPart(bodyPart); // Add attachment List<String> fileAddressList = new ArrayList<String>(); fileAddressList .add("C://Users//tuzongxun123//Desktop//New Microsoft Office Word document.docx"); if (fileAddressList != null) { BodyPart attachPart = null; for (int i = 0; i < fileAddressList.size(); i++) { if (!fileAddressList.get(i).isEmpty()) { attachPart = new MimeBodyPart(); // Attachment data source DataSource source = new FileDataSource( fileAddressList.get(i)); // Add the attachment data source to the mail body attachPart.setDataHandler(new DataHandler(source)); // Set the attachment name to the original file name attachPart.setFileName(MimeUtility.encodeText(source .getName())); mimeMultiPart.addBodyPart(attchPart); } } } message.setContent(mimeMultiPart); message.setSentDate(new Date()); // Save email message.saveChanges(); // Send email Transport.send(message); } } } class MailAuthenticator extends Authenticator { /** * Username*/ private String username; /** * Password*/ private String password; /** * Create a new instance MailAuthenticator. * * @param username * @param password */ public MailAuthenticator(String username, String password) { this.username = username; this.password = password; } public String getPassword() { return password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public void setUsername(String username) { this.username = username; } }Note: A colleague of mine used my code to replace it with his account and client authorization code. He reported an error as soon as he ran it. Then he reset the client authorization code of the email address, and the error disappeared.
The above is all about this article, I hope it will be helpful for everyone to learn Java programming.