1. JavaMailSender
2. Spring JavaMail发送文本邮件
3. Spring JavaMail发送HTML邮件
4. Spring JavaMail发送带图片的HTML邮件
5. Spring JavaMail发送带附件的邮件
1. JavaMailSender
<bean id="javaMailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:host="smtp.qq.com" p:username="xxx" p:password="xxx">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
</bean>
<bean id="sendMail" class="com.txazo.mail.SendMail">
<property name="javaMailSender" ref="javaMailSender" />
</bean>
2. Spring JavaMail发送文本邮件
public class SendMail {
public JavaMailSender javaMailSender;
public void send() {
SimpleMailMessage mail = new SimpleMailMessage();
try {
mail.setTo("[email protected]");
mail.setFrom("[email protected]");
mail.setSubject("Spring JavaMail Test");
mail.setText("This is a Spring JavaMail Test!");
javaMailSender.send(mail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Spring JavaMail发送HTML邮件
public class SendMail {
public JavaMailSender javaMailSender;
public void send() {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mailMessage, true, "utf-8");
messageHelper.setTo("[email protected]");
messageHelper.setFrom("[email protected]");
messageHelper.setSubject("Spring JavaMail Test");
messageHelper.setText("<html><head></head><body>"
+ "<a href='http://txazo.iteye.com'>"
+ "http://txazo.iteye.com</a></body></html>", true);
javaMailSender.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Spring JavaMail发送带图片的HTML邮件
public class SendMail {
public JavaMailSender javaMailSender;
public void send() {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mailMessage, true, "utf-8");
messageHelper.setTo("[email protected]");
messageHelper.setFrom("[email protected]");
messageHelper.setSubject("Spring JavaMail Test");
messageHelper.setText("<html><head></head><body>"
+ "<img src=\"cid:logo\" /></body></html>", true);
messageHelper.addInline("logo", new File("H://logo.jpg"));
javaMailSender.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. Spring JavaMail发送带附件的邮件
public class SendMail {
public JavaMailSender javaMailSender;
public void send() {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mailMessage, true, "utf-8");
messageHelper.setTo("[email protected]");
messageHelper.setFrom("[email protected]");
messageHelper.setSubject("Spring JavaMail Test");
messageHelper.setText("This is a Spring JavaMail Test!");
File file = new File("H://个人简历.doc");
messageHelper.addAttachment(
MimeUtility.encodeWord(file.getName()), file);
javaMailSender.send(mailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}