利用JavaMail发送邮件:smtp.163.com

一、利用JavaMail发送邮件案例:

1、maven项目结构:

2、先在pom.xml里边加入Javamail依赖,系统会根据坐标自动下载mail包(前提是配置好了maven):

3、配置email.properties属性文件,主要是为了不更改代码的前提下,该改变发送邮件的一些基本信息:

4、实现发送邮件的主体类SendMailUtils,代码下:

package top.hzelin.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



public class SendMailUtils {
    private static String from = "";
    private static String user = "";
    private static String password = "";
    /*
     * 读取属性文件的内容,并为上面上个属性赋初始值
     */
    static {
        Properties prop = new Properties();
        InputStream is = SendMailUtils.class.getClassLoader().getResourceAsStream("email.properties");
        try {
            prop.load(is);
            from = prop.getProperty("from");
            user=prop.getProperty("username");
            password=prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void sendMail(String to,String text,String title) {
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.163.com");//设置邮件服务器主机名
        props.put("mail.smtp.host", "smtp.163.com");
        props.put("mail.smtp.auth", "true");//发送服务器需要身份验证
        Session session = Session.getDefaultInstance(props);//设置环境信息
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        Multipart multipart = null;
        BodyPart contentPart = null;
        Transport transport = null;
        try {
            message.setFrom(from);//设置发件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(title);
            multipart = new MimeMultipart();//设置附件
            contentPart = new MimeBodyPart();
            contentPart.setContent(text, "text/html;charset=utf-8");
            multipart.addBodyPart(contentPart);
            message.setContent(multipart);
            message.saveChanges();
            transport = session.getTransport("smtp");
            transport.connect("smtp.163.com", user, password);
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        
        
        
    }

}

5、测试发送邮件功能是否可用SendEmailTest:

注意:email.properties配置文件中的密码应该是客户端授权码,不是登录密码,设置位置如下:

 

posted @ 2018-12-13 13:30  蔓延者  阅读(6433)  评论(0编辑  收藏  举报