发送QQ邮件
1.首先导入依赖架包
javax.mail
可以直接将
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
写进pom.xml里面,会自动下载,也可以自己下载架包,导入build path里面
spring-context-support
2.编写一个想要发给对方的随机码类
/**
*
*/
package com.zhiyou100.util;
/**
* @author Administrator
*
*/
public class RandomCode {
// 创建指定位数的随机数字符串
public static String createCode(int length) {
int[] arr = {0,1,2,3,4,5,6,7,8,9};
String code = "";
for (int i = 0; i <=length-1; i++) {
int random = (int)(Math.random()*10);
code += arr[random];
}
return code;
}
}
这个可以不要,要的话也不多余
3.创建JavaSendMail.java
/**
*
*/
package com.zhiyou100.util;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.zhiyou100.util.RandomCode;
/**
* @author Administrator
*
*/
public class JavaSendMail {
/*javaMailSenderImpl是spring封装的邮件发送封装类,
* 支持普通文件,附件,hrml。
* smtp 简易邮件传输通信协议 传送电子邮件
* host 邮件服务器主机
* */
private static final String HOST = "smtp.qq.com";
// 端口号
private static final Integer PORT = 25;
// 发件人账户
private static final String USERNAME = "你的邮箱";
/**
* 用QQ邮箱的SMTP邮件服务器,前提之一是关闭登录保护
* 开启邮箱登录保护,无法使用SMTP服务,若开启了,前往安全中心关闭
* qq邮箱16位授权码
*/
private static final String PASSWORD = "你的QQ授权码";
/**
* FROM发件人的账户和username的值相同
*/
private static final String EMAILFROM = "你的邮箱";
private static final JavaMailSenderImpl mailSender = createMailSender();
// 创建邮件发送服务器
private static JavaMailSenderImpl createMailSender() {
// TODO Auto-generated method stub
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
senderImpl.setHost(HOST);
senderImpl.setPort(PORT);
senderImpl.setUsername(USERNAME);
senderImpl.setPassword(PASSWORD);
senderImpl.setProtocol("smtp");
senderImpl.setDefaultEncoding("UTF-8");
// 添加认证机制
Properties properties = new Properties();
// mail.smtp.timeout:连接超时时间
properties.setProperty("mail.smtp.timeout", "25000");
// mail.smtp.auth:认证机制开关 记得开启
properties.setProperty("mail.smtp.auth", "true");
senderImpl.setJavaMailProperties(properties);
return senderImpl;
}
// 创建邮件,MimeMessage继承Message
public static void sendHtmlMail(String recipients,
String subject,
String code) {
// multpart 多部件
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper =
new MimeMessageHelper(mimeMessage, true, "UTF-8");
// 发送方
messageHelper.setFrom(EMAILFROM);
// to表示收件人
// 头表示主要收件人cc表示抄送人BCC表示秘密抄送人
messageHelper.setTo(recipients);
// 邮件主题
messageHelper.setSubject(subject);
// 邮件内容
messageHelper.setText(code);
// 发送邮件
mailSender.send(mimeMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
String code = RandomCode.createCode(6);
String subject = "系统消息";
String recipients = "接收人的邮箱";
sendHtmlMail(recipients, subject, code);
System.out.println("发送成功");
}
}
4.测试一下就可以了
简单的maven下的发送邮箱