1. 普通的JavaMail 发送和接受邮件
public class TestMail {
public static void main(String[] args) {
Transport transport = null;
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.163.com");
prop.put("mail.smtp.auth", true);
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "tramp");
}
};
Session session = Session.getDefaultInstance(prop, auth);
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
msg.setSubject("Test Mail");
msg.setSentDate(new Date());
msg.setText("how are you~");
transport = session.getTransport("smtp");
transport.send(msg);
System.out.println("send success");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
try {
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class JavaMailSSL {
public static void main(String argv[]) throws Exception {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props);
URLName urln = new URLName("pop3", "pop.163.com", 110, null,
"[email protected]", "tramp");
/*URLName urln = new URLName("pop3s", "pop.163.com", 995, null,
"[email protected]", "tramp");*/
Store store = session.getStore(urln);
Folder inbox = null;
try {
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
Message[] msgs = inbox.getMessages();
inbox.fetch(msgs, profile);
System.out.println("收件箱的邮件数:" + msgs.length);
for (int i = 0; i < msgs.length; i++) {
String from = msgs[i].getFrom()[0].toString();
InternetAddress ia = new InternetAddress(from);
System.out.println("-----------------------------");
System.out.println("发送者:" + ia.getPersonal() + "/"
+ ia.getAddress());
System.out.println("标题:" + msgs[i].getSubject());
System.out.println("大小:" + msgs[i].getSize());
System.out.println("时间:" + msgs[i].getSentDate());
}
} finally {
try {
inbox.close(false);
} catch (Exception e) {
}
try {
store.close();
} catch (Exception e) {
}
}
}
protected static String decodeText(String text)
throws UnsupportedEncodingException {
if (text == null)
return null;
if (text.startsWith("=?GB") || text.startsWith("=?gb"))
text = MimeUtility.decodeText(text);
else
text = new String(text.getBytes("ISO8859_1"));
return text;
}
}
2. Spring Mail 集成
@Service
public class MailService {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Autowired
private TaskExecutor taskExecutor;
public void sendSimpleMail() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("[email protected]");
msg.setTo("[email protected]");
msg.setReplyTo("[email protected]");
// 抄送
msg.setCc("[email protected]");
msg.setSubject("success login");
msg.setText("nice to meet you !!!");
this.javaMailSender.send(msg);
}
public void sendHtmlMail(String userName) throws MessagingException {
MimeMessage msg = this.javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("注册成功");
String htmlText = "<html><head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"
+ "</head><body>" + "恭喜,您在IBlog已经注册成功!您的用户ID为:"
+ "<font size='20' size='30'>" + userName + "</font>"
+ "</body></html>";
// true show it is a mail of html
helper.setText(htmlText, true);
this.javaMailSender.send(msg);
}
public void sendInlineMail() throws MessagingException {
MimeMessage msg = this.javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("注册成功");
String htmlText = "<html><head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"
+ "</head><body>" + "欢迎访问IBlog论坛!</hr>"
+ "<div><img src=\"cid:img01\"></img></div>" + "</body></html>";
// true show it is a mail of html
helper.setText(htmlText, true);
ClassPathResource resource = new ClassPathResource("1382946922292.jpg");
helper.addInline("img01", resource);
this.javaMailSender.send(msg);
}
public void sendAttachmentMail() throws MessagingException, IOException {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("注册成功");
helper.setText("欢迎访问宝宝淘论坛!");
ClassPathResource file1 = new ClassPathResource("bbt.zip");
helper.addAttachment("file01.zip", file1.getFile());
ClassPathResource file2 = new ClassPathResource("file.doc");
helper.addAttachment("file02.doc", file2.getFile());
javaMailSender.send(msg);
}
// 发送双版本邮件
public void sendAlternativeMail() throws Exception {
MimeMessagePreparator mmp = new MimeMessagePreparator() {
public void prepare(MimeMessage msg) throws Exception {
MimeMessageHelper helper = new MimeMessageHelper(msg, true,
"utf-8");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("注册成功");
MimeMultipart mmPart = new MimeMultipart("alternative");
msg.setContent(mmPart);
BodyPart plainTextPart = new MimeBodyPart();
plainTextPart.setText("欢迎访问宝宝淘论坛!");
mmPart.addBodyPart(plainTextPart);
BodyPart htmlPart = new MimeBodyPart();
String htmlText = "<html><head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"
+ "</head><body><font size='20' size='30'>"
+ "欢迎访问宝宝淘论坛</font>" + "</body></html>";
htmlPart.setContent(htmlText, "text/html;charset=utf-8");
mmPart.addBodyPart(htmlPart);
}
};
javaMailSender.send(mmp);
}
public void sendTemplateMail(String userId) throws MessagingException {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("注册成功:基于模板");
String htmlText = getMailContent(userId);
helper.setText(htmlText, true);
javaMailSender.send(msg);
}
public String getMailContent(String userId) {
String text = null;
try {
Template template = this.freeMarkerConfigurer.getConfiguration().getTemplate("registerUser.ftl");
Map<String, Object> map = new HashMap<String, Object>();
map.put("userId", userId);
text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
public void sendAsyncMail(final String userId) {
taskExecutor.execute(new Runnable() {
public void run() {
try {
sendTemplateMail(userId);
System.out.println("邮件发送成功!");
} catch (Exception e) {
System.out.println("邮件发送失败!,异常信息:" + e.getMessage());
}
}
});
}
}
<!-- spirng javamail config -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:host="smtp.163.com"
p:protocol="smtp"
p:defaultEncoding="utf8"
p:username="[email protected]"
p:password="tramp">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<!-- freemarker -->
<bean id="freeMarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
p:templateLoaderPath="classpath:template/">
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">1800</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
</props>
</property>
</bean>
<!-- 异步执行器 -->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
p:corePoolSize="10"
p:maxPoolSize="30" />