1.添加jar包
<!-- Javamail API --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.5</version> </dependency>
2.bean
<!-- 下面列出网易的SMTP服务器名和端口号: 网易邮箱 SMTP服务器 SMTP端口 POP3服务器 POP3端口 @126.com smtp.126.com 25 pop3.126.com 110 @163.com smtp.163.com 25 pop3.163.com 110 @yeah.net smtp.yeah.net 25 pop3.yeah.net 110 --> <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="protocol" value="${email.protocol}"/> <property name="host" value="${email.host}"/> <property name="port" value="${email.port}"/> <property name="username" value="${email.username}"/> <property name="password" value="${email.password}"/> <property name="defaultEncoding" value="UTF-8"></property> <property name="javaMailProperties"> <props> <prop key="mail.auth">${email.auth}</prop> <prop key="mail.smtp.timeout">${email.timout}</prop> </props> </property> </bean> <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage"> <!-- 发件人email --> <property name="from" value="${email.username}" /> <!--收件人email--> <property name="to" value="${email.default.to}" /> <!--email主题(标题)--> <property name="subject" value="${email.default.subject}" /> <!--email主题内容--> <property name="text"> <value>${email.default.text}</value> </property> </bean> <bean id="emailService" class="com.website.service.impl.EmailServiceImpl"> <property name="javaMailSender" ref="javaMailSender"/> <property name="simpleMailMessage" ref="simpleMailMessage"/> </bean>
3.email.properties
email.protocol=smtp email.host=smtp.163.com email.port=25 email.username=132312312@163.com email.password=yourpassword email.default.to=123121@126.com email.default.subject=Hello email.default.text=how are you email.auth=true email.timout=25000
4.发邮件代码:
public class EmailServiceImpl implements EmailService { private static final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class); private JavaMailSender javaMailSender; private SimpleMailMessage simpleMailMessage; /** * @方法名: sendMailSimple * @参数名:@param subject 邮件主题 * @参数名:@param content 邮件内容 * @参数名:@param to 收件人Email地址 * @描述语: 发送邮件 */ @Override public void sendMailSimple(String to, String subject, String content) throws Exception { try { //用于接收邮件的邮箱 simpleMailMessage.setTo(to); //邮件的主题 simpleMailMessage.setSubject(subject); //邮件的正文,第二个boolean类型的参数代表html格式 simpleMailMessage.setText(content); LOGGER.info("---------------------------{}", simpleMailMessage); //发送 javaMailSender.send(simpleMailMessage); } catch (Exception e) { throw new MessagingException("failed to send mail!", e); } } public void setJavaMailSender(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; } public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) { this.simpleMailMessage = simpleMailMessage; } }
需要注意的是有自己的服务邮箱就用这个,因为163,qq邮箱会有限制.
防止骚扰邮件:10分钟发一次很频繁,第一次10分钟,第二次半个小时,第三次1个小时,第四次12个小时.如果到了12个小时,这家店还没上线,继续12个小时.