java 工具类-----email

public class CommonMailSender implements MailSender {

 

private static final Log logger = LogFactory.getLog(CommonMailSender.class);

 

private MimeMessage mimeMsg; // MIME邮件对象

 

private Session session; // 邮件回话对象

 

private Properties props = new Properties();// 系统属性

    

private String user;

 

private String password;

 

public CommonMailSender(String smtpHost, String userName, String password) {

props.put("mail.host", smtpHost);

props.put("mail.localhost", smtpHost);

props.put("mail.smtp.host", smtpHost);

props.put("mail.smtp.localhost", smtpHost);

props.put("mail.smtp.auth", "true");

this.user = userName;

this.password = password;

props.setProperty("sun.jnu.encoding", "UTF-8");

}

 

public CommonMailSender(String smtpHost, int smtpPort,String userName, String password) {

props.put("mail.host", smtpHost);

props.put("mail.localhost", smtpHost);

props.put("mail.smtp.host", smtpHost);

props.put("mail.smtp.localhost", smtpHost);

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.port", smtpPort);

this.user = userName;

this.password = password;

props.setProperty("sun.jnu.encoding", "UTF-8");

}

 

public boolean doSend(CommonMail mail){

try {

session = Session.getDefaultInstance(props, null); // 获得邮件回话对象

mimeMsg = new MimeMessage(session);

mimeMsg.setFrom( new InternetAddress(mail.getFrom() ,mail.getFromName(),"UTF-8"));

List <String> toList = mail.getToList();

for( String to : toList ){

mimeMsg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

}

mimeMsg.setSubject( mail.getSubject(),"UTF-8");

mimeMsg.setContent(mail.getMultipart());

mimeMsg.saveChanges();

Transport transport = session.getTransport("smtp");

Integer smtpPort=(Integer)props.get("mail.smtp.port");

transport.connect((String)props.get("mail.smtp.host"),smtpPort==null?-1:smtpPort, user, password);

transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));

transport.close();

return true;

} catch (Exception e) {

logger.error(e.getMessage());

return false;

}

}

 

}

 

你可能感兴趣的:(java 工具类-----email)