书写一个发送邮件类

来源:互联网 发布:西门子ug软件侵权 编辑:程序博客网 时间:2024/06/07 23:08
public class MailUtil {public static void send(String add,String code){// 1. 创建一封邮件 Properties props = new Properties();       //获取163邮箱smtp服务器的地址,     props.setProperty("mail.host", "smtp.163.com");         //是否进行权限验证。 props.setProperty("mail.smtp.auth", "true");             Session session= Session.getDefaultInstance(props,new Authenticator() {        @Override        protected PasswordAuthentication getPasswordAuthentication() {        // TODO Auto-generated method stub        return new PasswordAuthentication("你的邮箱地址", "你的客户端授权密码");        }}); // 根据参数配置,创建会话对象(为了发送邮件准备的)        MimeMessage message = new MimeMessage(session);     // 创建邮件对象               // 2. From: 发件人        //    其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码        //    真正要发送时, 邮箱必须是真实有效的邮箱。        try {message.setFrom(new InternetAddress("你的邮箱地址", "小黑", "UTF-8"));// 3. To: 收件人 第一个参数是收件人邮箱  message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(add, "小白", "UTF-8"));  // 4. Subject: 邮件主题        message.setSubject("激活邮件", "UTF-8");        // 5. Content: 邮件正文(可以使用html标签)        message.setContent("<h1>激活邮件</h1><h3><a href='http://localhost:8080/javamail/user/yz?code="+code+"'> http://localhost:8080/javamail/user/yz?code="+code+"</a></h3>", "text/html;charset=UTF-8");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();}        try {        Transport.send(message);} catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();}      }}

这个授权码可以登陆你的163邮箱,然后点击设置,pop3,smtp这样的设置去设置。

对了这个需要使用第三方jar包

maven地址

 <dependency>
   <groupId>com.sun.mail</groupId>
   <artifactId>javax.mail</artifactId>
   <version>1.5.5</version>
</dependency>

0 0