58,454
社区成员
发帖
与我相关
我的任务
分享
package com.qj.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
* 用于Jmail返回邮箱账号和密码的校验(在这里被Jmail类所用)
*
* @author 朱志杰
*
*/
public class SMTPAuthenticator extends Authenticator {
private String name = "";
private String password = "";
public SMTPAuthenticator(String name, String password) {
this.name = name;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(name, password);
}
}
public void sendMail() throws Exception {
Properties props = new Properties();// 创建属性对象
props.put("mail.smtp.host", getHost());// 设置smtp服务器地址
props.put("mail.smtp.auth", "true");// 设置服务器smtp需要验证
Session session = Session.getInstance(props, null);// 创建新邮件并群发
// Session session = Session.getDefaultInstance(props);
// session.setDebug(true);
MimeMessage message = new MimeMessage(session);// 创建过程对象
message.setFrom(new InternetAddress(getFromAddr()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
getToAddr()));
message.setSubject(getTitle());// 设置主题
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(this.getSendtext(), "text/html;charset=GBK");// 设置信件内容
multipart.addBodyPart(contentPart);
if (getAttachPath() != null && getAttachName() != null) {
BodyPart attachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(getAttachPath());
attachmentPart.setDataHandler(new DataHandler(source));
BASE64Encoder enc = new BASE64Encoder();
attachmentPart.setFileName("=?GBK?B?"
+ enc.encode(getAttachName().getBytes()) + "?=");
multipart.addBodyPart(attachmentPart);
}
message.setContent(multipart);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, getUsername(), getPassword());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}