分享

用Java发送邮件(公司开发用的)

 dabinglibrary 2014-12-05

需要Jar包:mail-1.4.1.jar

public class EmailSender {
private static final String charset = "gbk";
private static final String defaultMimetype = "text/plain";

  /**
* 发送邮件
* @param receivers
*            收件人
* @param subject
*            标题
* @param mailContent
*            邮件内容
* @param attachements
*            附件
* @param mimetype
*            内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
* @param email
*            发送者邮箱
* @throws MessagingException 
* @throws UnsupportedEncodingException 
*/

public static void sendEmailMessage(String[] receivers, String subject,
String mailContent, File[] attachements, String mimetype, YiluEmail email) throws Exception {
final String url = email.getEmailUrl();   //***@163.com
final String password = email.getPassword(); //***
Properties props = new Properties();
props.put("mail.smtp.host", email.getSmtphost());// Smtp服务器地址:  smtp.163.com
props.put("mail.smtp.auth", "true");// 需要校验
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(url, password);// 登录用户名
}
});
// 测试
session.setDebug(false);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(email.getEmailUrl(), MimeUtility.encodeText(
ConfigUtil.getSystemMailSignname(), "GB2312", "B")));
// ConfigUtil.getSystemMailSignname() :\u4E00\u8DEF\u8D22\u5BCC
InternetAddress[] toAddress = new InternetAddress[receivers.length];
for (int i = 0; i < receivers.length; i++) {
toAddress[i] = new InternetAddress(receivers[i]);
}
mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);// 收件人邮件
mimeMessage.setSubject(subject, charset);
Multipart multipart = new MimeMultipart();
// 正文
MimeBodyPart body = new MimeBodyPart();
body.setContent(mailContent,
(mimetype != null && !"".equals(mimetype) ? mimetype
: defaultMimetype) + ";charset=" + charset);
multipart.addBodyPart(body);// 发件内容
// 附件
if (attachements != null) {
for (File attachement : attachements) {
MimeBodyPart attache = new MimeBodyPart();
// ByteArrayDataSource bads = new
// ByteArrayDataSource(byte[],"application/x-any");
attache.setDataHandler(new DataHandler(new FileDataSource(
attachement)));
String fileName = getLastName(attachement.getName());
attache.setFileName(MimeUtility.encodeText(fileName,
charset, null));
multipart.addBodyPart(attache);
}
}
mimeMessage.setContent(multipart);
mimeMessage.setSentDate(new Date());
Transport.send(mimeMessage);
}
private static String getLastName(String fileName) {
int pos = fileName.lastIndexOf("\\");
if (pos > -1) {
fileName = fileName.substring(pos + 1);
}
pos = fileName.lastIndexOf("/");
if (pos > -1) {
fileName = fileName.substring(pos + 1);
}
return fileName;
}
}



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多