我使用的阿里云的ecs服務(wù)器,網(wǎng)絡(luò)是專有網(wǎng)絡(luò),郵箱端口是25因苹,我使用javaMail始終發(fā),不出去郵箱苟耻。糾結(jié)了好長時間,才發(fā)現(xiàn)阿里的專有網(wǎng)絡(luò)把25端口給禁止了扶檐,所以只有用ssl的方式凶杖,也就是465。
代碼如下:
private static void createEmail(String myAccount, String receiveAccount, String code) {
// 1. 創(chuàng)建參數(shù)配置, 用于連接郵件服務(wù)器的參數(shù)配置
Properties props = new Properties(); // 參數(shù)配置
props.setProperty("mail.host", myEmailSMTPHost); // 發(fā)件人的郵箱的 SMTP 服務(wù)器地址
props.setProperty("mail.transport.protocol", "smtp"); // 使用的協(xié)議(JavaMail規(guī)范要求)
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465"); // 請求認(rèn)證款筑,參數(shù)名稱與具體實現(xiàn)有關(guān)
props.setProperty("mail.smtp.socketFactory.port", "465"); // 請求認(rèn)證智蝠,參數(shù)名稱與具體實現(xiàn)有關(guān)
props.setProperty("mail.smtp.auth", "true"); // 請求認(rèn)證,參數(shù)名稱與具體實現(xiàn)有關(guān)
// 2. 根據(jù)配置創(chuàng)建會話對象, 用于和郵件服務(wù)器交互
Session session = Session.getDefaultInstance(props);
session.setDebug(true); // 設(shè)置為debug模式, 可以查看詳細(xì)的發(fā)送 log
// 3. 創(chuàng)建一封郵件
MimeMessage message = null;
try {
message = createMimeMessage(session, myAccount, receiveAccount, code);
} catch (Exception e) {
e.printStackTrace();
}
// 4. 根據(jù) Session 獲取郵件傳輸對象
Transport transport = null;
try {
transport = session.getTransport();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
try {
// 5. 使用 郵箱賬號 和 密碼 連接郵件服務(wù)器
// 這里認(rèn)證的郵箱必須與 message 中的發(fā)件人郵箱一致奈梳,否則報錯
transport.connect(myAccount, myEmailPassword);
// 6. 發(fā)送郵件, 發(fā)到所有的收件地址, message.getAllRecipients() 獲取到的是在創(chuàng)建郵件對象時添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
}
// 7. 關(guān)閉連接
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}