黑马程序员技术交流社区
标题:
邮件发送公用类
[打印本页]
作者:
朱婵
时间:
2014-2-20 12:52
标题:
邮件发送公用类
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
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;
public class MailUtil {
public static void sendMail(Map<String,String> mailInstallMap,String subject, String text,List<String> bccs) throws Exception
{
String mailhost=mailInstallMap.get("mailhost").trim();//邮箱服务器
String port= mailInstallMap.get("port").trim();//邮箱服务器端口
String from= mailInstallMap.get("from").trim();//发件人
String file=null;//附件
final String password= mailInstallMap.get("password");//密码
final String user= mailInstallMap.get("user").trim();//用户名
Properties props = new Properties();
props.put("mail.smtp.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(props,new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
session.setDebug(false);
//构建邮件内容
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
for(String bccT:bccs )
{
String bcc=bccT.trim();
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc));
}
msg.setSubject(subject);
if (file != null) {
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(text);
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.attachFile(file);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
} else {
msg.setContent(text, "text/html;charset=UTF-8");
}
msg.saveChanges();
// 发送邮件
Transport.send(msg);
// System.out.println("\nMail was sent successfully.");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2