首页 资讯 社群 我的社区 搜索

在java程序中实现发送邮件的功能

zhupei
2018-10-12 16:22:54

  在这里简单的分享一个最基础的发邮件功能。

  首先我们需要去下载两个jar包,smtp.jar和mailapi.jar,导入到自己的项目中应该就不用我说了吧,大家都是有经验的开发人员了。

public class Demo1 {


public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getInstance(props);
session.setDebug(true);

Message msg = new MimeMessage(session);
msg.setText("邮件测试");
msg.setFrom(new InternetAddress("你的邮箱号"));

Transport transport = session.getTransport();
transport.connect("邮箱驱动", 25, "邮箱账号", "邮箱密码");
transport.sendMessage(msg,
new Address[]{new InternetAddress("对方的邮箱号")});

transport.close();
}

}

  这样就可以实现一个很简单的发邮件的功能,至于其他的高级功能的话可以下载我提供的这个文件去看,有非常详细的演示代码!
  我这里用的驱动是阿里云的,有的是可以使用使用搜狐或者163邮箱的也都是可以了!


  如果想做一些其它的功能的话可以利用邮箱找回密码,大致就是在你建表的时候要加上一个时间标志以及过期时间。

package com.soq.card.web.action;

import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.soq.card.biz.UserHander;
import com.soq.card.entity.Users;
import com.soq.card.tools.DBhepler;
import com.soq.card.tools.Mail;
import com.soq.card.tools.Md5;
import com.soq.card.web.base.BaseAction;

/**
* @author javen
* @Email zyw205@gmail.com
*
*/
public class PassEmailAction extends BaseAction {
private Users users;
private UserHander userHander;

private String email;
private String sid;
private String userName;

public String sendmail() {
try {
HibernateTemplate ht = this.getUserHander().getUsersDAO().getHibernateTemplate();
SessionFactory factory = ht.getSessionFactory();
Session session = factory.openSession();
Criteria criteria = session.createCriteria(Users.class);
criteria.add(Restrictions.eq("loginName", email));
List<Users> list = criteria.list();
if (list.size() > 0) {
users=list.get(0);
Mail mail = new Mail();

String secretKey = UUID.randomUUID().toString(); // 密钥
Timestamp outDate = new Timestamp(System.currentTimeMillis() + 30 * 60 * 1000);// 30分钟后过期
long date = outDate.getTime() / 1000 * 1000;// 忽略毫秒数 mySql 取出时间是忽略毫秒数的

DBhepler bhepler=new DBhepler();
String sql="update users set outDate=?,validataCode=? where loginName=?;";
String str[] ={outDate+"",secretKey,users.getLoginName()};
bhepler.AddU(sql, str);

//this.getUserHander().getUsersDAO().getHibernateTemplate().update(users); // 保存到数据库
System.out.println(" UserName>>>> "+users.getUserName());
String key =users.getUserName() + "$" + date + "$" + secretKey;
System.out.println(" key>>>"+key);
String digitalSignature = Md5.md5(key);// 数字签名

String path = this.getRequest().getContextPath();
String basePath = this.getRequest().getScheme() + "://"
+ this.getRequest().getServerName() + ":"
+ this.getRequest().getServerPort() + path + "/";
String resetPassHref = basePath + "checkLink?sid="
+ digitalSignature +"&userName="+users.getUserName();
String emailContent = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href="
+ resetPassHref + " target='_BLANK'>" + resetPassHref
+ "</a> 或者 <a href=" + resetPassHref
+ " target='_BLANK'>点击我重新设置密码</a>"
+ "<br/>tips:本邮件超过30分钟,链接将会失效,需要重新申请'找回密码'" + key
+ "t" + digitalSignature;

mail.setTo(email);
mail.setFrom("XX");// 你的邮箱
mail.setHost("smtp.163.com");
mail.setUsername("XXX@163.com");// 用户
mail.setPassword("CXXX");// 密码
mail.setSubject("[二维码名片]找回您的账户密码");
mail.setContent(emailContent);
if (mail.sendMail()) {
System.out.println(" 发送成功");
this.getRequest().setAttribute("mesg", "重置密码邮件已经发送,请登陆邮箱进行重置!");
return "sendMail";
}
} else {
this.getRequest().setAttribute("mesg", "用户名不存在,你不会忘记邮箱了吧?");
return "noUser";
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}

public String checkResetLink() {
System.out.println("sid>>>" + sid);

if (sid.equals("") || userName.equals("")) {
this.getRequest().setAttribute("mesg", "链接不完整,请重新生成");
System.out.println(">>>>> null");
return "error";
}
HibernateTemplate ht = this.getUserHander().getUsersDAO().getHibernateTemplate();
SessionFactory factory = ht.getSessionFactory();
Session session = factory.openSession();
Criteria criteria = session.createCriteria(Users.class);
criteria.add(Restrictions.eq("userName", userName));
List<Users> list = criteria.list();
if (list.size()>0) {
users=list.get(0);

Timestamp outDate = (Timestamp) users.getOutDate();
System.out.println("outDate>>>"+outDate);
if(outDate.getTime() <= System.currentTimeMillis()){ //表示已经过期
this.getRequest().setAttribute("mesg", "链接已经过期,请重新申请找回密码.");
System.out.println("时间 超时");
return "error";
}

String key = users.getUserName()+"$"+outDate.getTime()/1000*1000+"$"+users.getValidataCode();//数字签名

System.out.println("key link》》"+key);
String digitalSignature = Md5.md5(key);// 数字签名

System.out.println("digitalSignature>>>>"+digitalSignature);
if(!digitalSignature.equals(sid)) {
this.getRequest().setAttribute("mesg", "链接不正确,是否已经过期了?重新申请吧.");
System.out.println("标示不正确");
return "error";
}else {
//链接验证通过 转到修改密码页面
this.getRequest().setAttribute("user", users);
return "success";
}
}else {
this.getRequest().setAttribute("mesg", "链接错误,无法找到匹配用户,请重新申请找回密码.");
System.out.println("用户不存在");
return "error";
}
}

public Users getUsers() {
return users;
}

public void setUsers(Users users) {
this.users = users;
}

public UserHander getUserHander() {
return userHander;
}

public void setUserHander(UserHander userHander) {
this.userHander = userHander;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getSid() {
return sid;
}

public void setSid(String sid) {
this.sid = sid;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

}


用户评论