54 public static int sendMail(String account, String regemail, String url) {
try {
// 建立郵件會話
Properties props = new Properties(); // 用來在一個文件中存儲鍵-值對的,其中鍵和值是用等號分隔的
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);
// 由郵件會話新建一個消息對象
MimeMessage message = new MimeMessage(session);
// 設置發(fā)件人的地址
Address mail_from = new InternetAddress(Config.getConfig()
.getProperty("MAIL_FROM", 2));
message.setFrom(mail_from);
// 設置發(fā)件人的地址
Address mail_to = new InternetAddress(regemail);
message.setRecipient(Message.RecipientType.TO, mail_to);
// 設置標題
message.setSubject("百憶用戶注冊 - 郵箱確認");
// 設置郵件內(nèi)容格式,并防止亂碼出現(xiàn)
message.setContent(Javamails
.getEmailContent(account, regemail, url),
"text/html;charset=GBK");
// 設置發(fā)信時間
message.setSentDate(new Date());
log.debug("郵件標題: " + message.getSubject());
log.debug("郵件內(nèi)容: " + (String) message.getContent());
// 存儲郵件信息
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ā)送郵件,其中第二個參數(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;
} }
這里牽涉到讀取配置文件,好的項目,公用的話會寫到以.properties結(jié)尾的屬性文件里面###email配置MAIL_SERVER=60.191.25.164
MAIL_COUNT=*********(發(fā)送者郵箱前綴名稱)例如:houjunchang_daxue 結(jié)合下面的郵箱來寫MAIL_FROM=houjunchang_daxue@163.comMAIL_PASSWORD=郵箱密碼
|