1先去qq邮箱设置中开启 POP3和STMP 服务, 记住授权码
然后编写代码
package cn.yunhe.utils; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * 邮件发送工具类 * Created by Administrator on 2017/8/4. */ public class MailUtils { /** * 发送邮件的方法 * @param to :收件人 * @param code :激活码 */ public static void sendMail(String to,String code){ //1.获得Session对象 Properties props=new Properties(); props.put("mail.transport.protocol","smtp");//连接协议 props.put("mail.smtp.host","smtp.qq.com");//主机名 props.put("mail.smtp.port","465");//端口号 props.put("mail.smtp.auth","true"); props.put("mail.smtp.ssl.enable","true");//设置是否使用ssl安全连接,一般都使用 props.put("mail.debug","true");//设置是否显示debug信息 true会在控制台显示相关信息 //得到回话对象 Session session=Session.getInstance(props); //获取邮件对象 Message message=new MimeMessage(session); try { //设置发件人地址 message.setFrom(new InternetAddress("[email protected]")); //设置收件人地址 (将参数传进来) message.setRecipients(Message.RecipientType.TO,new InternetAddress[]{new InternetAddress(to)}); //设置邮件标题 message.setSubject("来自购物天堂的官方激活邮件"); //设置邮件正文 message.setContent("<h1>购物天堂官方激活邮件!点下边的链接完成激活操作!</h1><h3><a href=‘http://172.16.23.150:8080/user/active?code="+code+"‘>http://172.16.23.150:8080/active?code="+code+"</a></h3>","text/html;charset=UTF-8"); //得到邮差对象 Transport transport=session.getTransport(); //连接自己的邮箱账户 transport.connect("[email protected]","xvqeeiaszzvubhgg");//密码为授权码 //发送邮件 transport.sendMessage(message,message.getAllRecipients()); } catch (MessagingException e) { e.printStackTrace(); } //本地服务器 /*props.setProperty("mail.host","localhost");*/ /* Session session=Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]","111"); } });*/ //2.创建一个代表邮件的对象Message /*Message message=new MimeMessage(session); try { //设置发件人 message.setFrom(new InternetAddress("[email protected]")); //设置收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));//抄送 CC 密送 BCC //设置标题 message.setSubject("来自购物天堂的官方激活邮件"); //设置邮件正文 message.setContent("<h1>购物天堂官方激活邮件!点下边的链接完成激活操作!</h1><h3><a href=‘http://172.16.23.150:8080/user/active?code="+code+"‘>http://172.16.23.150:8080/active?code="+code+"</a></h3>","text/html;charset=UTF-8"); //3.发送邮件Transport Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); }*/ } }
时间: 2024-10-12 22:50:09