package ht.util;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendEmailUtil {
/**
* 邮件发送
* @param sfrom 发件人电子邮箱(需开通POP3/SMTP服务)
* @param spwd 发件人电子邮箱密码(qq邮箱为 授权码)
* @param sto 收件人电子邮箱
* @param shost 发送邮件的主机 例如 smtp.qq.com、smtp.163.com
* @param subject 邮箱标题
* @param text 邮件内容
* @param files 附件数组 例如 c:/1.jpg
* @return 成功true 失败false
*/
public static boolean sendEmail(final String sfrom, final String spwd, String sto, String shost, String subject,String text,String[] files) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", shost);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sfrom, spwd);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sfrom));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(sto));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(text);
Multipart multipart = new MimeMultipart();
for (String file : files) {
File usFile = new File(file);
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new FileDataSource(file);
fileBody.setDataHandler(new DataHandler(source));
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
fileBody.setFileName("=?GBK?B?" + enc.encode(usFile.getName().getBytes()) + "?=");
multipart.addBodyPart(fileBody);
}
message.setContent(multipart);
Transport.send(message);
return true;
} catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
}
}
JAVAMAIL实现发送邮件
最新推荐文章于 2024-01-12 14:39:39 发布