Java发送邮件

package cn.itcast;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.junit.Test;

/*
 * java Mail
 * */
public class SendMail {
    @Test
    public void fun1() throws MessagingException{
        /**
         * 1.得到session
         * */
        Properties props = new Properties();
        //设置服务器地址
        props.setProperty("mail.host", "smtp.163.com");
        //设置邮件服务器是否需要登陆认证
        props.setProperty("mail.smtp.auth", "true");
        //创建认证器
        Authenticator auth = new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("邮箱账号  注:不加@163之类的后缀","这时需要在163邮箱中开启smtp服务,这里真授权码而非密码");  
            }
        };
        //获取Session对象
        Session session = Session.getInstance(props,auth);
        /*
         * 2.创建mimeMessage
         * */
        //创建邮件对象
        MimeMessage msg = new MimeMessage(session);
        //设置发件人
        msg.setFrom(new InternetAddress("[email protected]"));
        //设置收件人,类型to
        msg.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
        //设置收件人,类型抄送
        msg.addRecipient(RecipientType.CC, new InternetAddress("[email protected]"));
        //设置收件人,类型暗送
        msg.addRecipient(RecipientType.BCC, new InternetAddress("[email protected]"));
        msg.setSubject("邮件的主题");
        msg.setContent("这里真写内容","text/html;charset=utf-8");
        //发邮件
//      Transport trans = session.getTransport("smtp");
//      trans.connect()
        Transport.send(msg);

    }

}

测试成功

你可能感兴趣的:(Java,Java,发送邮件,网易邮箱,IT,编程)