首页 > 编程语言 > 详细

java发送邮件

时间:2017-07-23 12:22:50      阅读:267      评论:0      收藏:0      [点我收藏+]

前提:导入发Java邮件的jar包:
activation.jar additionnal.jar(第三方客户端,没有时会) mail.jar
additionnal.jar(第三方客户端,没有时会出现在什么路径下,系统文件找不到)
步骤一:编写发邮件类
package com.gl.util;


import java.util.Properties

import javax.mail.*;
import javax.mail.internet.*;


public class MailUtil {
//传入发邮件的地址和邮件激活码
public static void sendMail(String to,String code){
//发送邮件的服务器
String host = "smtp.qq.com";
//用户名
String username="2238071096@qq.com";
//第三方客户端验证密码,需要在QQ邮箱的账户/SMTP/POP3/IMAP下开启/SMTP/POP3
//发短信得到第三方客户端登录验证密码
String password="************";
//Session对象
Properties props = new Properties();
props.put("mail.smtp.host", host);
//发送邮件的端口号
props.put("mail.smtp.port", "465");
/* props.put("mail.transport.protocol", "smtp");*/
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable","true");///使用 STARTTLS安全连接
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props);

//Message对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
try {
message.setFrom(new InternetAddress(username));
//设置收件人
message.setRecipients(Message.RecipientType.TO,to);
//设置主题
message.setSubject("来自于xionger商城的账号激活邮件");

//设置内容
message.setContent("<h1>来自于熊二商城的账号激活邮件!激活请点击以下链接</h1><br><h3><a href=‘http://localhost:8888/shop/usersActive.action?Users.u_code="+code+"‘>http://localhost:8888/shop/register.action?code="+code+"</a></h3>","text/html;charset=UTF-8");

message.saveChanges(); // implicit with send()

Transport transport = session.getTransport("smtp");

transport.connect(host, username, password);

transport.sendMessage(message, message.getAllRecipients());

transport.close();



} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
第二步:实现类,调用发邮件的方法(注册等等),此例是struts
public String Reg(){
UsersServiceImpl usersServiceImpl=(UsersServiceImpl) ac.getBean("usersService");
users.setU_state(false);
String u_code = UUID.randomUUID().toString().replace("-","");
System.out.println(u_code);
System.out.println(users.getU_email());
users.setU_code(u_code);
usersServiceImpl.save(users);
MailUtil.sendMail(users.getU_email(),u_code);
return "regOK";
}

 

java发送邮件

原文:http://www.cnblogs.com/yeyingyx/p/7224128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!