• 145534

    文章

  • 857

    评论

  • 13

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

JAVA 发送各种邮箱邮件 javamail


QQ邮箱

/**
     * 单条发送
     * @param mail  邮件对象,包含发送人、邮件主题、邮件内容
      * @param recipients 收件人
     * @throws AddressException
     * @throws MessagingException
     */
    public static void Send(MailPOJO mail) throws AddressException,MessagingException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(mail.getAddresser()));
        // 设置收件人邮箱地址 
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipients()));//一个收件人
        // 设置邮件标题
        message.setSubject(mail.getTheme());
        // 设置邮件内容
        message.setText(mail.getMailContent());
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(mail.getUSERNAME(), mail.getPASSWORD());// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * 群发
     * @param mail  邮件对象,包含发送人、邮件主题、邮件内容
      * @param recipients 收件人
     * @throws AddressException
     * @throws MessagingException
     */
    public static void Batch_send(MailPOJO mail,List<InternetAddress> olist) throws AddressException,MessagingException {
        //把收件人放入对象中
        InternetAddress[] recipients = new InternetAddress[olist.size()];
        for(int i = 0 ; i< olist.size() ;i++){
            recipients[i] = olist.get(i);
        }


        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");//设置发件人的SMTP服务器地址
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(mail.getAddresser()));
        // 设置收件人邮箱地址 
        message.setRecipients(Message.RecipientType.TO, recipients);//多个收件人
        // 抄送给自己
        message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(mail.getAddresser()));
        // 设置邮件标题
        message.setSubject(mail.getTheme());
        // 设置邮件内容
        message.setText(mail.getMailContent());
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(mail.getUSERNAME(), mail.getPASSWORD());// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

163邮箱

 static String HOST = "smtp.163.com"; // smtp服务器   

/** * 单条发送邮件(不带附件) * @param context 邮件内容 */ public static void send(MailPOJO mail,String recipients) { Properties properties = new Properties(); properties.put("mail.smtp.host", HOST);//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器) properties.setProperty("mail.transport.protocol", "smtp"); properties.put("mail.smtp.auth", "true"); //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条) Session session = Session.getDefaultInstance(properties);//用props对象构建一个session session.setDebug(true); MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象 try { message.setFrom(new InternetAddress(mail.getAddresser()));// 加载发件人地址 message.addRecipient(Message.RecipientType.TO,new InternetAddress(recipients));//加载收件人 message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(mail.getAddresser()));//设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错 message.setSubject(mail.getTheme());//加载标题 Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容 contentPart.setText(mail.getMailContent()); //放入邮件主题 multipart.addBodyPart(contentPart); message.setContent(multipart);//将multipart对象放到message中 message.saveChanges(); //保存邮件 Transport transport = session.getTransport("smtp");//发送邮件 transport.connect(HOST, mail.getUSERNAME(), mail.getPASSWORD());//连接服务器的邮箱 transport.sendMessage(message, message.getAllRecipients());//把邮件发送出去 transport.close();//关闭连接 } catch (Exception e) { e.printStackTrace(); } } /** * 批量发送邮件(不带附件) * @param TOS 收件人 * @param mail 邮件内容 */ public static void Batch_send(String[] TOS,MailPOJO mail) { Properties props = new Properties(); props.put("mail.smtp.host", HOST);//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器) props.setProperty("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条) Session session = Session.getDefaultInstance(props);//用props对象构建一个session session.setDebug(true); MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象 try { message.setFrom(new InternetAddress(mail.getAddresser()));// 加载发件人地址 InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加载收件人地址 for (int i = 0; i < TOS.length; i++) { sendTo[i] = new InternetAddress(TOS[i]); } message.addRecipients(Message.RecipientType.TO,sendTo); message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(mail.getAddresser()));//设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错 message.setSubject(mail.getMailContent());//加载标题 Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容 contentPart.setText(mail.getMailContent()); multipart.addBodyPart(contentPart); message.setContent(multipart);//将multipart对象放到message中 message.saveChanges(); //保存邮件 Transport transport = session.getTransport("smtp");//发送邮件 transport.connect(HOST, mail.getUSERNAME(), mail.getPASSWORD());//连接服务器的邮箱 transport.sendMessage(message, message.getAllRecipients());//把邮件发送出去 transport.close();//关闭连接 } catch (Exception e) { e.printStackTrace(); } }

Gmail邮箱

public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
        String to = "123@qq.com";//change accordingly

        // Sender's email ID needs to be mentioned
        String from = "123456";//change accordingly
        final String username = "123456@gmail.com";//账号
        final String password = "456789";//密码// Assuming you are sending email through relay.jangosmtp.net
        String host = "smtp.gmail.com";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.connectiontimeout", 1000*60);
        props.put("mail.smtp.timeout", 1000*60);
        props.put("mail.smtp.writetimeout", 1000*60);

        // Get the Session object.
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));

            // Set Subject: header field
            message.setSubject("Testing Subject");

            // Now set the actual message
            message.setText("Hello, this is sample for to check send "
                    + "email using JavaMailAPI ");

            // Send message
            Transport.send(message);

            System.out.println("Sent message successfully....");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

Outlook邮箱

/**
     * 带附件
     * @param mail  邮箱对象
     * @param to    收件人
     * @param File_Path    附件存放路径
     * @return
     */
    public static boolean sendMain(MailPOJO mail,String to,String File_Path) {
        //获取系统属性,主要用于设置邮件相关的参数。
        Properties properties = System.getProperties();
        //设置邮件传输服务器,由于本次是发送邮件操作,所需我们需要配置smtp协议,按outlook官方同步邮件的要求,依次配置协议地址,端口号和加密方法
        properties.setProperty("mail.smtp.host", "smtp.office365.com");
        properties.setProperty("mail.smtp.port", "587");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        //用户验证并返回Session,开启用户验证,设置发送邮箱的账号密码。
        properties.setProperty("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail.getUSERNAME(), mail.getPASSWORD());//账号密码
            }
        });

        //创建MimeMessage消息对象,消息头配置了收发邮箱的地址,消息体包含了邮件标题和邮件内容。接收者类型:TO代表直接发送,CC代表抄送,BCC代表秘密抄送。
        try {
            MimeMessage message = new MimeMessage(session);
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
            message.setFrom(new InternetAddress(mail.getAddresser()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(mail.getAddresser()));
            message.setSubject(mail.getTheme());


            // 1.创建复合消息体
            Multipart multipart = new MimeMultipart();
            // 2.添加附件
            BodyPart filePart = new MimeBodyPart();
            DataSource source = new FileDataSource(File_Path);//附件存放路径
            filePart.setDataHandler(new DataHandler(source));
            filePart.setFileName(source.getName());
            multipart.addBodyPart(filePart);
            // 3.添加文本内容
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(mail.getMailContent());
            multipart.addBodyPart(textPart);
            // 4.绑定消息对象
            message.setContent(multipart);
            // 5.发送邮件
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }



    /**
     * @Title: 发送outlook邮件
     * @Description: 需要outlook邮箱账号密码
     * @param: to        //收件人邮箱
     * @return: String
     * @throws 
     */
    public static boolean send(MailPOJO mail,String to) {
        //获取系统属性,主要用于设置邮件相关的参数。
        Properties properties = System.getProperties();
        //设置邮件传输服务器,由于本次是发送邮件操作,所需我们需要配置smtp协议,按outlook官方同步邮件的要求,依次配置协议地址,端口号和加密方法
        properties.setProperty("mail.smtp.host", "smtp.office365.com");
        properties.setProperty("mail.smtp.port", "587");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        //用户验证并返回Session,开启用户验证,设置发送邮箱的账号密码。
        properties.setProperty("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail.getUSERNAME(), mail.getPASSWORD());//账号密码
            }
        });

        //创建MimeMessage消息对象,消息头配置了收发邮箱的地址,消息体包含了邮件标题和邮件内容。接收者类型:TO代表直接发送,CC代表抄送,BCC代表秘密抄送。
        try {
            MimeMessage message = new MimeMessage(session);
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
            message.setFrom(new InternetAddress(mail.getAddresser()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(mail.getAddresser()));
            message.setSubject(mail.getTheme());


            // 1.创建复合消息体
            Multipart multipart = new MimeMultipart();
            // 2.添加文本内容
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(mail.getMailContent());
            multipart.addBodyPart(textPart);
            // 3.绑定消息对象
            message.setContent(multipart);
            // 4.发送邮件
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

Yandex邮箱

/**
     * 
     * @param from    账号
     * @param pass    密码
     * @param to    收件人邮箱
     * @param subject    主题
     * @param body    正文
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendFromYandex(String from, String pass, String to, String subject, String body) throws AddressException, MessagingException {
        Properties props = System.getProperties();
        String host = "smtp.yandex.com";
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.quitwait", "false");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.debug", "true");

        Session session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        message.setHeader("Content-Type", "text/plain; charset=UTF-8");
        message.setSubject(subject, "UTF-8");
        message.setText(body, "UTF-8");

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress toAddress = new InternetAddress(to);
            message.addRecipient(Message.RecipientType.TO, toAddress);
            //设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(to));

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (AddressException ae) {
            ae.printStackTrace();
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

mailPOJO

/**
 * 邮箱对象
 * @author JM.H
 *
 */
public class MailPOJO {
    
    //收件人
    private String recipients;
    //发件人
    private String addresser;
    //邮件主题
    private String theme;
    //邮件内容
    private String MailContent;
    //发送的邮箱账号
    private String USERNAME;
    //发送的邮箱密码
    private String PASSWORD;
    
    
    public String getAddresser() {
        return addresser;
    }
    public void setAddresser(String addresser) {
        this.addresser = addresser;
    }
    public String getTheme() {
        return theme;
    }
    public void setTheme(String theme) {
        this.theme = theme;
    }
    public String getMailContent() {
        return MailContent;
    }
    public void setMailContent(String mailContent) {
        MailContent = mailContent;
    }
    public String getUSERNAME() {
        return USERNAME;
    }
    public void setUSERNAME(String uSERNAME) {
        USERNAME = uSERNAME;
    }
    public String getPASSWORD() {
        return PASSWORD;
    }
    public void setPASSWORD(String pASSWORD) {
        PASSWORD = pASSWORD;
    }
    public String getRecipients() {
        return recipients;
    }
    public void setRecipients(String recipients) {
        this.recipients = recipients;
    }
    
}

 MAVEN

<!-- 邮件发送APIhttps://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.ews-java-api</groupId>
            <artifactId>ews-java-api</artifactId>
            <version>2.0</version>
        </dependency>

 Z-Blog:http://www.361wx.com


695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

0条评论

Loading...


发表评论

电子邮件地址不会被公开。 必填项已用*标注

自定义皮肤 主体内容背景
打开支付宝扫码付款购买视频教程
遇到问题联系客服QQ:419400980
注册梁钟霖个人博客