spring mail的使用

首先 applicationContext.xml中配置一个bean,使用 org.springframework.mail.javamail.JavaMailSenderImpl类并注入参数,如下:


<bean id="gmailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="username" value="[email protected]"/>
<property name="password" value="panjinfeng" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
</props>
</property>
</bean>
使用它:
[img]file:///C:/DOCUME%7E1/pan/LOCALS%7E1/Temp/moz-screenshot.jpg[/img]public class Test {
/**
* @param args
*/
public static void main(String[] args) {
boolean bool = true;
Log log = LogFactory.getLog(Test.class);
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
log.debug("after load applicationContext.xml! ");
JavaMailSender gmailSender = (JavaMailSender) context
.getBean("gmailSender");
/*
SimpleMailMessage mail0 = new SimpleMailMessage();
mail0.setFrom("[email protected]");
mail0.setTo("[email protected]");
mail0.setSubject("spring Mail");
mail0.setText("sfsdfsdfsdfsdf");

log.debug("befor send gmail");
try {
log.debug("sending gmail..............");
gmailSender.send(mail0);
} catch (Exception e) {
log.error(" 邮件发送失败!");
bool = false;
e.printStackTrace();
}
if(bool){
log.debug("gmail send mail success");
}*/

MimeMessage mime = gmailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mime,true,"gb2312");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setText("hahahahhahahaha");
helper.setSubject("attachment");
helper.addAttachment("en.txt", new ClassPathResource("javaeye.txt"));
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.toString();
e.printStackTrace();
}
try {
log.debug("sending gmail..............");
gmailSender.send(mime);
} catch (Exception e) {
log.error(" 邮件发送失败!");
bool = false;
e.printStackTrace();
}
if(bool){
log.debug("gmail send mail success");
}
}
}

你可能感兴趣的:(spring)