1.需要jar包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
去除冲突包
<exclusions>
<exclusion>
<artifactId>geronimo-spec-javamail</artifactId>
<groupId>geronimo-spec</groupId>
</exclusion>
</exclusions>
2.mail.properties
#配置服务器邮件账号信息
#服务器
mail.smtp.host=smtp.mxhichina.com
#是否需要验证密码
mail.smtp.auth=true
#超时时间
mail.smtp.timeout=25000
#发件人信箱
mail.smtp.from=zhanghongmiao@changchong.com.cn
#用户名
mail.smtp.username=zhanghongmiao@changchong.com.cn
#密码
mail.smtp.password=zhm-399211
3.spring.xml
<!-- 配置邮件 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.smtp.host}"></property>
<property name="javaMailProperties" >
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
<prop key="mail.smtp.from">${mail.smtp.from}</prop>
</props>
</property>
<property name="username" value="${mail.smtp.username}"></property>
<property name="password" value="${mail.smtp.password}"></property>
</bean>
4.java
import java.util.Properties;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.changchong.service.MailService;
@Service("mailService")
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSenderImpl senderImpl;
public void sendHtml(String htmlMsg,String title,String sendTo) throws Exception {
Properties p = senderImpl.getJavaMailProperties();
//建立邮件消息,发送简单邮件和html邮件的区别
MimeMessage mailMessage = senderImpl.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true,"UTF-8");
//设置收件人,寄件人
messageHelper.setTo(sendTo);
messageHelper.setFrom(p.getProperty("mail.smtp.from"));
messageHelper.setSubject(title);
//true 表示启动HTML格式的邮件
messageHelper.setText(htmlMsg,true);
//发送邮件
senderImpl.send(mailMessage);
}
}
5.调用,如果权限验证失败,检查用户名密码
try {
mailService.sendHtml("hello 你好", "找回密码", "113363434@qq.com");
} catch (Exception e) {
LOGGER.error("邮件发送失败:"+e.getMessage());
}