/**
* 向QQ邮箱发送消息
* @param sendToQQ
* @param content
* @throws GeneralSecurityException
* @throws MessagingException
*/
public static void sendMessageToMail(String sendToQQ,String content) throws GeneralSecurityException, MessagingException {
Properties pro = new Properties();
// 开启debug调试
pro.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
pro.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
pro.setProperty("mail.host", "smtp.qq.com");
// 发送邮件协议名称
pro.setProperty("mail.transport.protocol", "smtp");
// 固定这么写
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
pro.put("mail.smtp.ssl.enble", "true");
pro.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(pro);
Message msg = new MimeMessage(session);
msg.setSubject("验证码");
msg.setText(content);
// 设置发送人
msg.setFrom(new InternetAddress("364621561@qq.com"));
Transport transport = session.getTransport();
// 设置密令
transport.connect("smtp.qq.com", "364621561@qq.com", "yrxypofwypbybgfh");
//设置收件人
transport.sendMessage(msg, new Address[]{new InternetAddress(sendToQQ)});
transport.close();
}
配置bean
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.qq.com" /><!--设置邮件服务主机-->
<property name="username" value="364621561@qq.com" /><!--/发送者邮箱的用户名 -->
<property name="password" value="yrxypofwypbybgfh" /><!--//发送者邮箱的密码这块内容写密令-->
<property name="port" value="25" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
调用程序
JavaMailSender mailSender;
/**
*
* @param url 可以是一个controller层的一个方法
* @param receive 接收人
* @throws MessagingException
*/
public void sendCodeImg(String url,String receive) throws MessagingException {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg,true,"utf-8");
// 设置发送人
helper.setFrom("364621561@qq.com");
// 设置收件人
helper.setTo(receive);
// 该邮件的主题
helper.setSubject("MiaoMiao影厅");
// 设置发送的内容
helper.setText("<span><img src='"+ url +"'></img></span>",true);
// 发送
mailSender.send(msg)
}