1.导入jar包
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
2.代码案例
import org.jboss.cache.factories.annotations.Start;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
public class MailUtils {
/**
* @param to 收件人
* @param content 邮件的内容
* @param subject 邮件的主题
*/
public static boolean sendMail(String subject,String to,String content){
//设置发送邮件的协议为smtp
//props.put("mail.transport.protocol","SMTP");
//发送邮件的服务器地址 本地 localhost
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com");//根据不同的邮箱服务器进行修改
//设置安全认证为true
props.put("mail.smtp.auth", "true");
props.put("mail.username","xxxxxxxxxxx@qq.com" );
props.put("mail.password", "xxxxxxxxxxx");
//创建密码校验器
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 设置连接邮件的用户名和密码
return new PasswordAuthentication("xxxxxxxxxxx@qq.com", "xxxxxxxxxxx");//连接服务器的用户名和密码
}
};
//创建邮件的会话对象
Session session = Session.getInstance(props, auth);
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件给谁发送 TO正常发送的邮件
try {
//设置发送邮件的邮箱
message.setFrom(new InternetAddress("xxxxxxxxxxx@qq.com"));
//设置收件人
message.addRecipient(RecipientType.TO, new InternetAddress(to));
//设置邮件主题
message.setSubject(subject);
//设置邮件的内容
message.setContent(content,"text/html;charset=UTF-8");
//发送邮件
Transport.send(message);
} catch (Exception e) {
// TODO Auto-generated catch block
System.err.println("邮件发送失败的原因是:"+e.getMessage());
System.err.println("具体的错误原因");
e.printStackTrace(System.err);
return false;
}
return true;
}
public static final char[] chars={'1','2','3','4','5','6','7','8','9','0'};
public static Random random=new Random();
public static String getVerificationCode(){
StringBuffer sb=new StringBuffer();
for(int i=0;i<=5;i++){
sb.append(chars[random.nextInt(chars.length)]);;
}
return sb.toString();
}
//测试
public static void main(String[] args) {
String s = getVerificationCode();
sendMail("验证码","xxxxxxxxxxx@qq.com"," 您的验证码是: "+s);
System.out.println("邮件发送完毕 "+s);
}
}