54 public static int sendMail(String account, String regemail, String url) {
try {
// 建立郵件會(huì)話
Properties props = new Properties(); // 用來(lái)在一個(gè)文件中存儲(chǔ)鍵-值對(duì)的,其中鍵和值是用等號(hào)分隔的
props.put("mail.smtp.host", Config.getConfig().getProperty(
"MAIL_SERVER", 2));
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
// 由郵件會(huì)話新建一個(gè)消息對(duì)象
MimeMessage message = new MimeMessage(session);
// 設(shè)置發(fā)件人的地址
Address mail_from = new InternetAddress(Config.getConfig()
.getProperty("MAIL_FROM", 2));
message.setFrom(mail_from);
// 設(shè)置發(fā)件人的地址
Address mail_to = new InternetAddress(regemail);
message.setRecipient(Message.RecipientType.TO, mail_to);
// 設(shè)置標(biāo)題
message.setSubject("百憶用戶注冊(cè) - 郵箱確認(rèn)");
// 設(shè)置郵件內(nèi)容格式,并防止亂碼出現(xiàn)
message.setContent(Javamails
.getEmailContent(account, regemail, url),
"text/html;charset=GBK");
// 設(shè)置發(fā)信時(shí)間
message.setSentDate(new Date());
log.debug("郵件標(biāo)題: " + message.getSubject());
log.debug("郵件內(nèi)容: " + (String) message.getContent());
// 存儲(chǔ)郵件信息
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(Config.getConfig().getProperty("MAIL_SERVER", 2),
Config.getConfig().getProperty("MAIL_COUNT", 2), Config
.getConfig().getProperty("MAIL_PASSWORD", 2));
// 發(fā)送郵件,其中第二個(gè)參數(shù)是所有已設(shè)好的收件人地址
transport.sendMessage(message, message.getAllRecipients());
transport.close();
log.debug("success");
return 1;
} catch (AddressException e) {
e.printStackTrace();
log.error("Address is Exception");
return 0;
} catch (MessagingException e) {
e.printStackTrace();
log.error("Messaging is Exception");
return 0;
} catch (Exception e) {
e.printStackTrace();
log.error("read monkey.properties failed");
return 0;
} }
這里牽涉到讀取配置文件,好的項(xiàng)目,公用的話會(huì)寫(xiě)到以.properties結(jié)尾的屬性文件里面###email配置MAIL_SERVER=60.191.25.164
MAIL_COUNT=*********(發(fā)送者郵箱前綴名稱)例如:houjunchang_daxue 結(jié)合下面的郵箱來(lái)寫(xiě)MAIL_FROM=houjunchang_daxue@163.comMAIL_PASSWORD=郵箱密碼
|