Spring中使用JavaMailSenderImpl发送邮件

2016-03-29· 8473 次浏览
### ApplicationContext.xml: ```html <!-- JavaMail相关配置 --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl" > <property name="host" value="发件服务器"></property> <property name="username" value="用户名"></property> <property name="password" value="密码"></property> <property name="protocol" value="smtp"></property> <property name="defaultEncoding" value="utf-8"></property> <property name="javaMailProperties">      <props>        <prop key="mail.smtp.auth">true</prop>        <prop key="mail.smtp.from">demo@zhenzhigu.com</prop>        <prop key="mail.debug">true</prop>    </props> </property> </bean> ``` ### 使用注解从Spring容器中注入mailSender对象: ``` @Autowired private JavaMailSenderImpl sender; ``` 准备一封简单的邮件: ``` // 构建简单邮件对象,见名知意 SimpleMailMessage smm = new SimpleMailMessage(); // 设定邮件参数 smm.setFrom(sender.getUsername()); smm.setTo("1500506007@qq.com"); smm.setSubject("Hello world"); smm.setText("Hello world via spring mail sender"); ``` 发送邮件: ``` sender.send(smm); ``` 如果你想发送带有附件的邮件: ```java /**  * 发送带附件的邮件,可指定附件名  * @param to  * @param subject  * @param text  * @param file  * @throws MessagingException  */ public static void send(String to,String subject,String text,      String fileName,File file) throws MessagigException{     //使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容     MimeMessage msg = sender.createMimeMessage();       //创建MimeMessageHelper对象,处理MimeMessage的辅助类     MimeMessageHelper helper = new MimeMessageHelper(msg, true);       //使用辅助类MimeMessage设定参数     helper.setFrom(sender.getUsername());     helper.setTo(to);     helper.setSubject(subject);     helper.setText(text,true);               //加入附件     if(file!=null)helper.addAttachment(fileName, file);       //发送邮件     sender.send(msg); } ```