下載和上傳附件、發送短信和發送郵件,都算是程序中很常用的功能,之前記錄了文件的上傳和下載還有發送短信,由於最近比較忙,郵件發送的功能就沒有時間去弄,現在終於成功以163郵箱發送郵件到qq郵箱,以下是相關代碼,具體解釋可以參考代碼中註釋:
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 郵件發送測試類// */ public class sendMailTest { public static void main(String[] args) throws Exception { // 配置信息Properties pro = new Properties(); pro.put("mail.smtp.host", "smtp.163.com"); pro.put("mail.smtp.auth", "true"); // SSL加密MailSSLSocketFactory sf = null; sf = new MailSSLSocketFactory(); // 設置信任所有的主機sf.setTrustAllHosts(true); pro.put("mail.smtp.ssl.enable", "true"); pro.put("mail.smtp.ssl.socketFactory", sf); // 根據郵件的會話屬性構造一個發送郵件的Session,這裡需要注意的是用戶名那裡不能加後綴,否則便不是用戶名了//還需要注意的是,這裡的密碼不是正常使用郵箱的登陸密碼,而是客戶端生成的另一個專門的授權碼MailAuthenticator authenticator = new MailAuthenticator("tuzongxun123", "客戶端授權碼"); Session session = Session.getInstance(pro, authenticator); // 根據Session 構建郵件信息Message message = new MimeMessage(session); // 創建郵件發送者地址Address from = new InternetAddress("[email protected]"); // 設置郵件消息的發送者message.setFrom(from); // 驗證收件人郵箱地址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()) { // 創建郵件的接收者地址Address[] to = InternetAddress.parse(toAddress); // 設置郵件接收人地址message.setRecipients(Message.RecipientType.TO, to); // 郵件主題// message.setSubject("java郵件測試"); message.setSubject("為什麼錯了"); // 郵件容器MimeMultipart mimeMultiPart = new MimeMultipart(); // 設置HTML BodyPart bodyPart = new MimeBodyPart(); // 郵件內容// String htmlText = "java郵件測試111"; String htmlText = "為什麼錯了"; bodyPart.setContent(htmlText, "text/html;charset=utf-8"); mimeMultiPart.addBodyPart(bodyPart); // 添加附件List<String> fileAddressList = new ArrayList<String>(); fileAddressList .add("C://Users//tuzongxun123//Desktop//新建Microsoft Office Word 文檔.docx"); if (fileAddressList != null) { BodyPart attchPart = null; for (int i = 0; i < fileAddressList.size(); i++) { if (!fileAddressList.get(i).isEmpty()) { attchPart = new MimeBodyPart(); // 附件數據源DataSource source = new FileDataSource( fileAddressList.get(i)); // 將附件數據源添加到郵件體attchPart.setDataHandler(new DataHandler(source)); // 設置附件名稱為原文件名attchPart.setFileName(MimeUtility.encodeText(source .getName())); mimeMultiPart.addBodyPart(attchPart); } } } message.setContent(mimeMultiPart); message.setSentDate(new Date()); // 保存郵件message.saveChanges(); // 發送郵件Transport.send(message); } } } class MailAuthenticator extends Authenticator { /** * 用戶名*/ private String username; /** * 密碼*/ private String password; /** * 創建一個新的實例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; } }注:我有個同事使用我這個代碼更換為他的賬號和客戶端授權碼後,一運行就報錯,然後重置了一下郵箱的客戶端授權碼後,錯誤便消失了。
以上就是本文的全部內容,希望對大家學習java程序設計有所幫助。