public void setSender(String sender)
{
this.sender = sender;
}
public String getSender()
{
return sender;
}
/** 設定郵件發送伺服器(smtp) */
public void setSmtpHost(String smtpHost) {this.smtpHost = smtpHost;}
public String getSmtpHost() {return smtpHost;}
/** 設定登入使用者名稱 */
public void setUser(String user)
{
this.user = user;
}
public String getUser()
{
return user;
}
/** 設定登入密碼 */
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}
/** 設定mail主題 */
public void setSubject(String subject)
{
this.subject = subject;
}
public String getSubject()
{
return subject;
}
/**
* 使用smtp發送郵件 主程式
* @throws MessagingException mail發送失敗
*/
public void smtp(String receiver,String content) throws MessagingException
{
if (smtpHost == null) throw new MessagingException("smtpHost not found");
if (user == null) throw new MessagingException("user not found");
if (password == null) throw new MessagingException("password not found");
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);//設定smtp主機
properties.put("mail.smtp.auth", "true");//使用smtp身分識別驗證
Session session = Session.getDefaultInstance(properties,
new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user, password);
}
});
//獲得郵件會話對象
MimeMessage mimeMsg = new MimeMessage(session);//建立MIME郵件對象
if (sender != null)//設定寄件者地址
{
mimeMsg.setFrom(new InternetAddress(sender));
}
if (receiver != null)//設定收件者地址
{
mimeMsg.setRecipients(Message.RecipientType.TO, parse(receiver));
}
if (subject != null)//設定郵件主題
{
mimeMsg.setSubject(subject, "GBK");
}
MimeBodyPart part = new MimeBodyPart();//mail內容部分
part.setText(content == null ? "" : content, "GBK");