/**
- 表示邮件类,你需要设置:账户名和密码、收件人、抄送(可选)、暗送(可选)、主题、内容,以及附件(可选)
- 在创建了Mail对象之后
- 可以调用它的setSubject()、setContent(),设置主题和正文
- 也可以调用setFrom()和 addToAddress(),设置发件人,和添加收件人。
- 也可以调用addAttch()添加附件
-
创建AttachBean:new AttachBean(new File("..."), "fileName");
*/
public class Mail {
private String from;//发件人
private StringBuilder toAddress = new StringBuilder();//收件人
private StringBuilder ccAddress = new StringBuilder();//抄送
private StringBuilder bccAddress = new StringBuilder();//暗送private String subject;//主题
private String content;//正文// 附件列表
private List attachList = new ArrayList();public Mail() {}
public Mail(String from, String to) {
this(from, to, null, null);
}public Mail(String from, String to, String subject, String content) {
this.from = from;
this.toAddress.append(to);
this.subject = subject;
this.content = content;
}/**
- 返回发件人
- @return */ public void setFrom(String from) { this.from = from; }
/**
- 返回发件人
- @return */ public String getFrom() { return from; }
/**
- 返回主题 */ public String getSubject() { return subject; }
/**
- 设置主题 */ public void setSubject(String subject) { this.subject = subject; }
/**
- 获取主题内容 */ public String getContent() { return content; }
/**
- 设置主题内容
- @param content */ public void setContent(String content) { this.content = content; }
/**
- 获取收件人
- @return */ public String getToAddress() { return toAddress.toString(); }
/**
- 获取抄送
- @return */ public String getCcAddress() { return ccAddress.toString(); }
/**
- 获取暗送
- @return */ public String getBccAddress() { return bccAddress.toString(); }
/**
- 添加收件人,可以是多个收件人
- @param to */ public void addToAddress(String to) { if(this.toAddress.length() > 0) { this.toAddress.append(","); } this.toAddress.append(to); }
/**
- 添加抄送人,可以是多个抄送人
- @param cc */ public void addCcAddress(String cc) { if(this.ccAddress.length() > 0) { this.ccAddress.append(","); } this.ccAddress.append(cc); }
/**
- 添加暗送人,可以是多个暗送人
- @param bcc */ public void addBccAddress(String bcc) { if(this.bccAddress.length() > 0) { this.bccAddress.append(","); } this.bccAddress.append(bcc); }
/**
- 添加附件,可以添加多个附件
- @param attachBean */ public void addAttach(AttachBean attachBean) { this.attachList.add(attachBean); }
/**
- 获取所有附件
- @return */ public List getAttachs() { return this.attachList; } }
/*
-
附件类,只有文件,即附件才文件名
*/
public class AttachBean {
private String cid;
private File file;
private String fileName;public String getCid() {
return cid;
}public void setCid(String cid) {
this.cid = cid;
}public File getFile() {
return file;
}public void setFile(File file) {
this.file = file;
}public String getFileName() {
return fileName;
}public void setFileName(String fileName) {
this.fileName = fileName;
}public AttachBean() {
}
public AttachBean(File file, String fileName) {
super();
this.file = file;
this.fileName = fileName;
}
}
/**
-
@author itcast 本类只有这么一个方法,用来发邮件!
*/
public class MailUtils {
public static Session createSession(String host, final String username, final String password) {
Properties prop = new Properties();
prop.setProperty("mail.host", host);// 指定主机
prop.setProperty("mail.smtp.auth", "true");// 指定验证为true// 创建验证器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }; // 获取session对象 return Session.getInstance(prop, auth);
}
/**
- 发送指定的邮件
-
@param mail
*/
public static void send(Session session, final Mail mail) throws MessagingException,
IOException {MimeMessage msg = new MimeMessage(session);// 创建邮件对象
msg.setFrom(new InternetAddress(mail.getFrom()));// 设置发件人
msg.addRecipients(RecipientType.TO, mail.getToAddress());// 设置收件人// 设置抄送
String cc = mail.getCcAddress();
if (!cc.isEmpty()) {
msg.addRecipients(RecipientType.CC, cc);
}// 设置暗送
String bcc = mail.getBccAddress();
if (!bcc.isEmpty()) {
msg.addRecipients(RecipientType.BCC, bcc);
}msg.setSubject(mail.getSubject());// 设置主题
MimeMultipart parts = new MimeMultipart();// 创建部件集对象
MimeBodyPart part = new MimeBodyPart();// 创建一个部件
part.setContent(mail.getContent(), "text/html;charset=utf-8");// 设置邮件文本内容
parts.addBodyPart(part);// 把部件添加到部件集中///////////////////////////////////////////
// 添加附件
List attachBeanList = mail.getAttachs();// 获取所有附件
if (attachBeanList != null) {
for (AttachBean attach : attachBeanList) {
MimeBodyPart attachPart = new MimeBodyPart();// 创建一个部件
attachPart.attachFile(attach.getFile());// 设置附件文件
attachPart.setFileName(MimeUtility.encodeText(attach
.getFileName()));// 设置附件文件名
String cid = attach.getCid();
if(cid != null) {
attachPart.setContentID(cid);
}
parts.addBodyPart(attachPart);
}
}msg.setContent(parts);// 给邮件设置内容
Transport.send(msg);// 发邮件
}
}
email_template.properties类
subject=\u6765\u81EAITCAST\u7684\u6FC0\u6D3B\u90AE\u4EF6
content=\u606D\u559C\uFF0C\u60A8\u5DF2\u6CE8\u518C\u6210\u529F\uFF0C\u8BF7\u8F6C\u53D1\u8FD9\u91CC\u5B8C\u6210\u6FC0\u6D3B\u3002
from=33333@qq.com
host=smtp.qq.com
username=33333
password=33333
/*
* 3. 发邮件
/
/
* 把配置文件内容加载到prop中
/
Properties prop = new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
/
* 登录邮件服务器,得到session
*/
String host = prop.getProperty("host");//服务器主机名
String name = prop.getProperty("username");//登录名
String pass = prop.getProperty("password");//登录密码
Session session = MailUtils.createSession(host, name, pass);
/*
* 创建Mail对象
*/
String from = prop.getProperty("from");
String to = user.getEmail();
String subject = prop.getProperty("subject");
// MessageForm.format方法会把第一个参数中的{0},使用第二个参数来替换。
// 例如MessageFormat.format("你好{0}, 你{1}!", "张三", "去死吧"); 返回“你好张三,你去死吧!”
String content = MessageFormat.format(prop.getProperty("content"), user.getActivationCode());
Mail mail = new Mail(from, to, subject, content);
/*
* 发送邮件
*/
try {
MailUtils.send(session, mail);
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
错误:严重: Servlet.service() for servlet UserServlet threw exception
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at cn.itcast.servlet.BaseServlet.service(BaseServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at cn.itcast.filter.EncodingFilter.doFilter(EncodingFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at cn.itcast.servlet.BaseServlet.service(BaseServlet.java:44)
... 16 more
Caused by: java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect
at cn.itcast.goods.user.service.UserService.regist(UserService.java:144)
at cn.itcast.goods.user.web.servlet.UserServlet.regist(UserServlet.java:133)
... 21 more
Caused by: javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:322)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at cn.itcast.mail.MailUtils.send(MailUtils.java:91)
at cn.itcast.goods.user.service.UserService.regist(UserService.java:142)
... 22 more