javaMail发送邮件

来源:互联网 发布:matlab矩阵循环赋值 编辑:程序博客网 时间:2024/06/06 03:26

javaMail发送邮件
可自行更改

package mail;import java.util.Properties;import java.util.Random;import javax.mail.Authenticator;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMessage.RecipientType;import org.junit.Test;/** * javamail第一例 * @author 刘乃杰 * 17.6.14 * */public class Demo02 {    @Test    public void fun1() throws AddressException, MessagingException{        /**         * 1.得到session         */        Properties props=new Properties();        props.setProperty("mail.host","smtp.163.com");    //设置邮件服务器地址    /*不同邮箱:smtp:xxx.com*/        props.setProperty("mail.smtp.auth","true");        //设置邮件服务器是否需要认证        //创建认证器        Authenticator auth=new Authenticator() {                public PasswordAuthentication getPasswordAuthentication(){                    return new PasswordAuthentication("xxx","xxx");                    //指定用户名和密码/*用户名不需加后缀   例:xxx@163.com    只需写xxx*/                }        };        //获取session对象        Session session=Session.getInstance(props,auth);        /**         * 2.创建mimemessage         */        MimeMessage msg=new MimeMessage(session);        msg.setFrom(new InternetAddress("xxx"));        //设置发件人        msg.addRecipient(RecipientType.TO,new InternetAddress("xxxx"));    //设置收件人//        msg.addRecipient(RecipientType.CC,new InternetAddress("xxxx"));    //类型为抄送//        msg.addRecipient(RecipientType.BCC,new InternetAddress("xxxx"));//类型为密送        msg.setSubject("这是一封测试邮件");    //设置邮件的主题        //指定内容,及内容的mime类型        Random rand = new Random();        int yzm = rand.nextInt(1000);        msg.setContent("验证码为:["+yzm+"]","text/html;charset=utf-8");        /**         * 3.发邮件         */        Transport.send(msg);    }}
原创粉丝点击