zoukankan      html  css  js  c++  java
  • javamail发送邮件

    邮件协议概述:
    与Http协议相同,收发邮件也是需要有传输协议的。
    *SMIP: Simple Mail Transfer Protocol 简单传输协议,发邮件协议
    *POP3:Post Office Protocol Version 3,邮局协议第三版,收邮件协议
    *IMAP:Internet Message Access Protocol,因特网消息访问协议,收发邮件协议

    ============================
    javaMail

    1.导包!
    *mail.jar
    *activation.jar

    -----------------
    核心类
    1.Session
    *如果你得到了它,表示已经与服务器连接上了,与Connection的作用相似

    得到Session,需要使用Session.getInstance(Properties,Authentication);
    2.MemeMessage
    *它表示一个邮件对象,你可以调用它的setForm().可以设置发件人,收件人,主题,正文

    3.TransPort
    *它只有一个功能,发邮件!

    我的qq邮箱有点问题,没有成功!

    package cn.itcast.javamail;
    
    import java.io.File;
    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.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeUtility;
    import javax.mail.internet.MimeMessage.RecipientType;
    import javax.mail.internet.MimeMultipart;
    
    import org.junit.Test;
    
    
    public class Demo1 {
        
        @Test
        public void fun1() throws AddressException, MessagingException{
            /*
             * 1.得到session
             */
            Properties props=new Properties();
            props.setProperty("mail.host", "smtp.qq.com");//服务器主机名
            props.setProperty("mail.smtp.auth", "true");//是否验证
            
            Authenticator auth=new Authenticator(){
    
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("3291984010@qq.com","961012gz");//用户名密码
                }
                
            };
            
            Session session=Session.getInstance(props,auth);
            /*
             * 2.创建MimeMessage
             * 401753187
             */
            MimeMessage msg=new MimeMessage(session);
            msg.setFrom(new InternetAddress("3291984010@qq.com"));//发件人
            msg.setRecipients(RecipientType.TO, "401753187@qq.com");//收件人
            msg.setRecipients(RecipientType.BCC,"1580909730@qq.com");//抄送
            msg.setRecipients(RecipientType.CC, "1430566269");//暗送
            
            msg.setSubject("这是一封测试邮件");//标题
            msg.setContent("这就是一封垃圾邮件", "text/html;charset=utf-8");//正文
            
            /*
             * 发
             */
            Transport.send(msg);
        }
        
        public void test02() throws Exception{
            /*
             * 1.得到session
             */
            Properties props=new Properties();
            props.setProperty("mail.host", "smtp.qq.com");//服务器主机名
            props.setProperty("mail.smtp.auth", "true");//是否验证
            
            Authenticator auth=new Authenticator(){
    
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("3291984010@qq.com","961012gz");//用户名密码
                }
                
            };
            
            Session session=Session.getInstance(props,auth);
            /*
             * 2.创建MimeMessage
             * 401753187
             */
            MimeMessage msg=new MimeMessage(session);
            msg.setFrom(new InternetAddress("3291984010@qq.com"));//发件人
            msg.setRecipients(RecipientType.TO, "401753187@qq.com");//收件人
            msg.setRecipients(RecipientType.BCC,"1580909730@qq.com");//抄送
            msg.setRecipients(RecipientType.CC, "1430566269");//暗送
            
            msg.setSubject("这是一封测试邮件");//标题
    
            
            //设置主题部分的内容,这里使用的是类似包裹的方式
            MimeMultipart list=new MimeMultipart();//创建多部分的内容
            
            MimeBodyPart part1=new MimeBodyPart();//创建主体部件1
            part1.setContent("这是一封包含附件的垃圾邮件", "text/html;charset=utf-8");
            list.addBodyPart(part1);
            
            MimeBodyPart part2=new MimeBodyPart();//创建主体部件2
            part2.attachFile(new File("F:/f/白冰.jpg"));//增加附件内容
    //        part2.setFileName("大美女.jpg");//设置显示的文件名
            part2.setFileName(MimeUtility.encodeText("大美女.jpg"));//处理了中文乱码
            list.addBodyPart(part2);
            /*
             * 发
             */
            Transport.send(msg);
        }
    }

    自定义工具类:

    package cn.itcast.mail;
    
    import java.io.File;
    
    /*
     * 附件类,只有文件,即附件才文件名
     */
    public class AttachBean {
        private String cid;
        private File file;
        private String fileName;
    
        public String getCid() {
            return cid;
        }
    
        public void setCid(String cid) {
            this.cid = cid;
        }
        
        public File getFile() {
            return file;
        }
    
        public void setFile(File file) {
            this.file = file;
        }
    
        public String getFileName() {
            return fileName;
        }
    
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
    
        public AttachBean() {
    
        }
    
        public AttachBean(File file, String fileName) {
            super();
            this.file = file;
            this.fileName = fileName;
        }
    }
    
    
    package cn.itcast.mail;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 表示邮件类,你需要设置:账户名和密码、收件人、抄送(可选)、暗送(可选)、主题、内容,以及附件(可选)
     * 
     * 在创建了Mail对象之后
     * 可以调用它的setSubject()、setContent(),设置主题和正文
     * 也可以调用setFrom()和 addToAddress(),设置发件人,和添加收件人。
     * 也可以调用addAttch()添加附件
     * 创建AttachBean:new AttachBean(new File("..."), "fileName");
     */
    public class Mail {
        private String from;//发件人
        private StringBuilder toAddress = new StringBuilder();//收件人
        private StringBuilder ccAddress = new StringBuilder();//抄送
        private StringBuilder bccAddress = new StringBuilder();//暗送
        
        private String subject;//主题
        private String content;//正文
        
        // 附件列表
        private List<AttachBean> attachList = new ArrayList<AttachBean>();
        
        public Mail() {}
        
        public Mail(String from, String to) {
            this(from, to, null, null);
        }
        
        public Mail(String from, String to, String subject, String content) {
            this.from = from;
            this.toAddress.append(to);
            this.subject = subject;
            this.content = content;
        }
        
        /**
         * 返回发件人
         * @return
         */
        public void setFrom(String from) {
            this.from = from;
        }
        
        /**
         * 返回发件人
         * @return
         */
        public String getFrom() {
            return from;
        }
        
        /**
         * 返回主题
         */
        public String getSubject() {
            return subject;
        }
    
        /**
         * 设置主题
         */
        public void setSubject(String subject) {
            this.subject = subject;
        }
    
        /**
         * 获取主题内容
         */
        public String getContent() {
            return content;
        }
    
        /**
         * 设置主题内容
         * @param content
         */
        public void setContent(String content) {
            this.content = content;
        }
    
        /**
         * 获取收件人
         * @return
         */
        public String getToAddress() {
            return toAddress.toString();
        }
    
        /**
         * 获取抄送
         * @return
         */
        public String getCcAddress() {
            return ccAddress.toString();
        }
    
        /**
         * 获取暗送
         * @return
         */
        public String getBccAddress() {
            return bccAddress.toString();
        }
    
        /**
         * 添加收件人,可以是多个收件人
         * @param to
         */
        public void addToAddress(String to) {
            if(this.toAddress.length() > 0) {
                this.toAddress.append(",");
            }
            this.toAddress.append(to);
        }
    
        /**
         * 添加抄送人,可以是多个抄送人
         * @param cc
         */
        public void addCcAddress(String cc) {
            if(this.ccAddress.length() > 0) {
                this.ccAddress.append(",");
            }
            this.ccAddress.append(cc);
        }
    
        /**
         * 添加暗送人,可以是多个暗送人
         * @param bcc
         */
        public void addBccAddress(String bcc) {
            if(this.bccAddress.length() > 0) {
                this.bccAddress.append(",");
            }
            this.bccAddress.append(bcc);
        }
        
        /**
         * 添加附件,可以添加多个附件
         * @param attachBean
         */
        public void addAttach(AttachBean attachBean) {
            this.attachList.add(attachBean);
        }
        
        /**
         * 获取所有附件
         * @return
         */
        public List<AttachBean> getAttachs() {
            return this.attachList;
        }
    }
    
    
    package cn.itcast.mail;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message.RecipientType;
    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.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.internet.MimeUtility;
    
    /**
     * 
     * @author itcast 本类只有这么一个方法,用来发邮件!
     */
    public class MailUtils {
        public static Session createSession(String host, final String username, final String password) {
            Properties prop = new Properties();
            prop.setProperty("mail.host", host);// 指定主机
            prop.setProperty("mail.smtp.auth", "true");// 指定验证为true
    
            // 创建验证器
            Authenticator auth = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            };
            
            // 获取session对象
            return Session.getInstance(prop, auth);
        }
        
        /**
         * 发送指定的邮件
         * 
         * @param mail
         */
        public static void send(Session session, final Mail mail) throws MessagingException,
                IOException {
    
            MimeMessage msg = new MimeMessage(session);// 创建邮件对象
            msg.setFrom(new InternetAddress(mail.getFrom()));// 设置发件人
            msg.addRecipients(RecipientType.TO, mail.getToAddress());// 设置收件人
    
            // 设置抄送
            String cc = mail.getCcAddress();
            if (!cc.isEmpty()) {
                msg.addRecipients(RecipientType.CC, cc);
            }
    
            // 设置暗送
            String bcc = mail.getBccAddress();
            if (!bcc.isEmpty()) {
                msg.addRecipients(RecipientType.BCC, bcc);
            }
    
            msg.setSubject(mail.getSubject());// 设置主题
    
            MimeMultipart parts = new MimeMultipart();// 创建部件集对象
    
            MimeBodyPart part = new MimeBodyPart();// 创建一个部件
            part.setContent(mail.getContent(), "text/html;charset=utf-8");// 设置邮件文本内容
            parts.addBodyPart(part);// 把部件添加到部件集中
            
            ///////////////////////////////////////////
    
            // 添加附件
            List<AttachBean> attachBeanList = mail.getAttachs();// 获取所有附件
            if (attachBeanList != null) {
                for (AttachBean attach : attachBeanList) {
                    MimeBodyPart attachPart = new MimeBodyPart();// 创建一个部件
                    attachPart.attachFile(attach.getFile());// 设置附件文件
                    attachPart.setFileName(MimeUtility.encodeText(attach
                            .getFileName()));// 设置附件文件名
                    String cid = attach.getCid();
                    if(cid != null) {
                        attachPart.setContentID(cid);
                    }
                    parts.addBodyPart(attachPart);
                }
            }
    
            msg.setContent(parts);// 给邮件设置内容
            Transport.send(msg);// 发邮件
        }
    }
    View Code

    使用自定义工具类:

    @Test
        public void fun3() throws Exception {
            /*
             * 1. 得到session
             */
            Session session = MailUtils.createSession("smtp.163.com", 
                    "itcast_cxf", "itcast");
            /*
             * 2. 创建邮件对象
             */
            Mail mail = new Mail("itcast_cxf@163.com",
                    "itcast_cxf@126.com,itcast_cxf@sina.com",
                    "不是垃圾邮件能是什么呢?", "这里是正文");
            
            /*
             * 创建两个附件对象
             */
            AttachBean ab1 = new AttachBean(new File("F:/f/白冰.jpg"), "小美女.jpg");
            AttachBean ab2 = new AttachBean(new File("F:/f/big.jpg"), "我的羽绒服.jpg");
            
            // 添加到mail中
            mail.addAttach(ab1);
            mail.addAttach(ab2);
            
            /*
             * 3. 发送
             */
            MailUtils.send(session, mail);
        }
    View Code
  • 相关阅读:
    拓扑编号
    奇怪的梦境
    奖金
    最优布线问题
    亲戚
    最小花费
    Dijkstra算法 最短路径 (部分)
    Floyed算法 最短路径
    P1164 小A点菜(背包方案数模板)
    P1049 装箱问题
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5748222.html
Copyright © 2011-2022 走看看