Spring邮件发送1
注意:邮件发送code中,邮件服务器的申请和配置是比较主要的一个环节,博主这里用的是QQ的邮件服务器。有需要的可以谷歌、百度查下如何开通。
今天看了下Spring的官方文档的邮件发送这一章节。在这里记录一下初次学习成果。详细使用方案如下:
1. 申请邮箱服务器,用于发送邮件。
2. 在项目中引入用于支持java邮件发送的jar包
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version>
</dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
3. 配置java邮件发送器
邮件发送器配置: applicationContext-mail.xml
<!-- Define mail sender util bean -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="protocol" value="#{config['mail.protocol']}" />
<property name="host" value="#{config['mail.host']}" />
<property name="port" value="#{config['mail.port']}" />
<property name="username" value="#{config['mail.username']}" />
<property name="password" value="#{config['mail.password']}" />
<property name="defaultEncoding" value="#{config['mail.default.encoding']}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">#{config['mail.smtp.auth']}</prop>
<prop key="mail.smtp.starttls.enable">#{config['mail.smtp.starttls.enable']}</prop>
<prop key="mail.smtp.timeout">#{config['mail.smtp.timeout']}</prop>
</props>
</property>
</bean>
邮件发送器属性文件
mail.protocol=smtp mail.host=smtp.qq.com mail.port=587 mail.username=发件人邮箱 mail.password=邮箱授权 mail.default.encoding=UTF-8 mail.smtp.auth=true mail.smtp.starttls.enable=true mail.smtp.timeout=25000
4. 编写邮件发送处理器
接口:
/** * send text email * * @param email recipients email address * @param subject * @param content * @return send mail result */ public boolean sendText(String email, String subject, String content); /** * send email with attachment * * @param email * @param subject * @param content * @param attachments * @return */
public boolean sendAttachment(String email, String subject, String content, File...attachments);
1). 发送文本邮件
MimeMessage mimeMessage = mailSender.createMimeMessage(); // Indicate this is multipart message & indicate encoding MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding); helper.setFrom(form); // set sender helper.setTo(to); // set recipients helper.setSubject(subject); helper.setText(content, true); // Indicate the text included is HTML // Send mail mailSender.send(mimeMessage);
2). 发送带附件邮件
MimeMessage mimeMessage = mailSender.createMimeMessage(); // Indicate this is multipart message & indicate encoding MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding); helper.setFrom(form); // set sender helper.setTo(to); // set recipients helper.setSubject(subject); helper.setText(content, true); // Indicate the text included is HTML // Indicate with attachment for (File attachment : attachments) { helper.addAttachment(attachment.getName(), attachment); } // Send mail mailSender.send(mimeMessage);