• JAVA实用案例之邮件发送


    最近有朋友问邮件怎么发送,就简单写了个demo,因为懒得找jar包,所以项目是创建的maven工程,具体的maven引用的jar如下:

    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.4.4</version>
    </dependency>
    
    
    <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>

    然后代码见下:

    1、整合demo

    因为QQ是https所以中间多了一段,还有就是如果自己搭的邮件服务器可以填写密码,而不用授权码了,这里我是用的QQ邮箱,所以邮箱要先开启SMTP/POP3服务

    package com.allan.until;
    
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    import com.sun.mail.util.MailSSLSocketFactory;
    
    public class MailUtil  {
        private String email;// 收件人邮箱
        private String code;// 激活码
    
        public MailUtil(String email, String code) {
            this.email = email;
            this.code = code;
        }
    
        public void sendMail() {
            // 1.创建连接对象javax.mail.Session
            // 2.创建邮件对象 javax.mail.Message
            // 3.发送一封激活邮件
            String from = "XXX@qq.com";// 发件人电子邮箱
            String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
    
            //Properties properties = System.getProperties();// 获取系统属性
            Properties properties =new Properties();
    
            properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
            properties.setProperty("mail.smtp.auth", "true");// 打开认证
    
            try {
                //QQ邮箱需要下面这段代码,163邮箱不需要
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                properties.put("mail.smtp.ssl.enable", "true");
                properties.put("mail.smtp.ssl.socketFactory", sf);
    
    
                // 1.获取默认session对象
                Session session = Session.getDefaultInstance(properties, new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("XXX@qq.com", "XXX"); // 发件人邮箱账号、授权码
                    }
                });
    
                // 2.创建邮件对象
                Message message = new MimeMessage(session);
                // 2.1设置发件人
                message.setFrom(new InternetAddress(from));
                // 2.2设置接收人
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
                // 2.3设置邮件主题
                message.setSubject("账号激活");
                // 2.4设置邮件内容
                String content = "验证码:"+ code;
                message.setContent(content, "text/html;charset=UTF-8");
                // 3.发送邮件
                Transport.send(message);
                System.out.println("邮件成功发送!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }

     附件版:

    package com.aitou.operation.utils;
    
    import java.io.InputStream;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    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;
    import javax.mail.internet.MimeUtility;
    import javax.mail.util.ByteArrayDataSource;
    
    import com.sun.mail.util.MailSSLSocketFactory;
    
    public class MailUtil {
        /** 
         *  
         * 方法名: sendMail  
         * 描述: 发送邮件 
         * 创建人: zhangzhuo
         * 参数: @param subject 
         * 参数: @param toMail 
         * 参数: @param content 
         * 参数: @param files 
         * 参数: @return 
         * 返回类型: boolean 
         */  
        public static boolean sendMail(String fromMail, String password, String subject, String toMail, String content,
                List<InputStream> listIs, List<String> listName) {    
            boolean isFlag = false;    
            try {    
                String smtpFromMail = fromMail;  //账号    
                String pwd = password; //密码    
                String host = "smtp.qq.com"; //端口    
        
                Properties props = new Properties();
                props.put("mail.smtp.host", host);
                props.put("mail.smtp.auth", "true");
                //QQ邮箱
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.smtp.ssl.enable", "true");
                props.put("mail.smtp.ssl.socketFactory", sf);
                
                Session session = Session.getDefaultInstance(props);
                session.setDebug(false);    
    
                MimeMessage message = new MimeMessage(session);
                try {    
                    message.setFrom(new InternetAddress(smtpFromMail));
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
                    message.setSubject(subject);
                    message.addHeader("charset", "UTF-8");
                        
                    /*添加正文内容*/    
                    Multipart multipart = new MimeMultipart();
                    BodyPart contentPart = new MimeBodyPart();
                    contentPart.setText(content);
        
                    //contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
                    multipart.addBodyPart(contentPart);
                        
                    /*添加附件*/
                    for (int i = 0; i < listIs.size(); i++) {
                        MimeBodyPart fileBody = new MimeBodyPart();
                        DataSource source = new ByteArrayDataSource(listIs.get(i), "application/msexcel");
                        fileBody.setDataHandler(new DataHandler(source));
                        String fileName  = listName.get(i);
                        // 中文乱码问题  
                        fileBody.setFileName(MimeUtility.encodeText(fileName));
                        multipart.addBodyPart(fileBody);
                    }
        
                    message.setContent(multipart);
                    message.setSentDate(new Date());
                    message.saveChanges();
                    Transport transport = session.getTransport("smtp");
        
                    transport.connect(host, smtpFromMail, pwd);
                    transport.sendMessage(message, message.getAllRecipients());
                    transport.close();
                    isFlag = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    isFlag = false;
                }    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return isFlag;
        }    
    }

    2、spring整合javamail

    工具提取:

    public class MailUtil {
        
        
        /**
         * 发送电子邮件
         * @param addr 收件人地址
         * @param subject 主题
         * @param text 内容
         * @throws MessagingException
         */
        public static void sendMail(String addr,String subject,String text) throws MessagingException{
            Properties props=new Properties();
            props.put("mail.smtp.host","smtp.sina.com");
            props.put("mail.smtp.auth","true");
            Session session=Session.getInstance(props);
            //构造信息体&nbsp;
            MimeMessage message =new MimeMessage(session);
             //发件地址&nbsp;
            Address address = new InternetAddress("wwwitcastcn@sina.com"); 
            message.setFrom(address);
            //收件地址&nbsp;
            Address toAddress = new InternetAddress(addr); 
            message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
            //主题&nbsp;
            message.setSubject(subject);
            //正文&nbsp;
            message.setText(text);
            message.saveChanges();
            Transport transport = session.getTransport("smtp"); 
            transport.connect("smtp.sina.com", "wwwitcastcn@sina.com", "itcast"); //发送&nbsp;
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            
        }
        
    }

    Spring对javamail的支持:

    Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender,和其对象SimpleMailMessage,它封装了简单邮件的属性如fromto,ccsubject,text。 包里还包含一棵以MailException为根的checked Exception继承树,它们提供了对底层邮件系统异常的高级别抽象。 要获得关于邮件异常层次的更丰富的信息。

    为了使用JavaMail中的一些特色, 比如MIME类型的信件, spring提供了MailSender的一个子接口, 即org.springframework.mail.javamail.JavaMailSender。Spring还提供了一个回调接口org.springframework.mail.javamail.MimeMessagePreparator, 用于准备JavaMail的MIME信件。

    这里简单的介绍了如何使用spring发送各种形式的邮件以及配置。

    1、在src目录下建立mail.properties文件里边包含一下内容

    mail.host=smtp.qq.com

    mail.username=你的邮箱名
    mail.password=你的邮箱密码
    mail.from=发送方的邮箱

    2、使用spring配置

    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans
              xmlns="http://www.springframework.org/schema/beans"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:p="http://www.springframework.org/schema/p"
              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
     <!-- 加载Properties文件 -->  
        <beanid="configurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
            <propertyname="locations">  
                <list>  
                    <value>classpath:mail.properties</value>  
                </list>  
            </property>  
        </bean>  
        <beanid="mailMessage"class="org.springframework.mail.SimpleMailMessage">  
            <propertyname="from">  
                <value>${mail.from}</value>  
            </property>  
            <!-- 查看SimpleMailMessage源码还可以注入标题,内容等 -->  
        </bean>  
        <!-- 申明JavaMailSenderImpl对象 -->  
        <beanid="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl">  
            <propertyname="defaultEncoding"value="UTF-8"/>  
            <propertyname="host"value="${mail.host}"/>  
            <propertyname="username"value="${mail.username}"/>  
            <propertyname="password"value="${mail.password}"/>  
            <propertyname="javaMailProperties">  
                <props>  
                    <!-- 设置认证开关 -->  
                    <propkey="mail.smtp.auth">true</prop>  
                    <!-- 启动调试开关 -->  
                    <propkey="mail.debug">true</prop>  
                    <!-- 设置发送延时 -->
                    <propkey="mail.smtp.timeout">0</prop>
                </props>  
            </property>  
        </bean>  
    </beans>

    3、发送简单邮件

    importjavax.mail.MessagingException; 
    importorg.springframework.context.ApplicationContext;
    importorg.springframework.context.support.ClassPathXmlApplicationContext;
    importorg.springframework.mail.MailSender;
    importorg.springframework.mail.SimpleMailMessage;
    public class SingleMailSend {
        static ApplicationContext actx = new ClassPathXmlApplicationContext("applicationContext.xml");
        static MailSender sender = (MailSender) actx.getBean("mailSender");
        static SimpleMailMessage mailMessage = (SimpleMailMessage) actx.getBean("mailMessage");
    
        public static void main(String[] args) throws MessagingException {
            mailMessage.setSubject("??");
            mailMessage.setText("这个是一个通过Spring框架来发送邮件的小程序"); 
         mailMessage.setTo(
    "XXX@qq.com");
         sender.send(mailMessage);
    }
    }

    4、发送带有图片的邮件,以嵌入HTML的方式

    importjava.io.File;
    importjavax.mail.MessagingException;
    importjavax.mail.internet.MimeMessage;
    importorg.springframework.context.ApplicationContext;
    importorg.springframework.context.support.ClassPathXmlApplicationContext;
    importorg.springframework.core.io.FileSystemResource;
    importorg.springframework.mail.javamail.JavaMailSenderImpl;
    importorg.springframework.mail.javamail.MimeMessageHelper;

    public class SpringAttachedImageMail {

    public static voidmain(String[] args) throws MessagingException {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    JavaMailSenderImpl sender = (JavaMailSenderImpl) ctx.getBean("mailSender");
    MimeMessage mailMessage = sender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);
    messageHelper.setFrom("9197****1@qq.com");
    messageHelper.setTo("9197****1@qq.com");
    messageHelper.setSubject("测试邮件中嵌套图片!!");// true 表示启动HTML格式的邮件
    messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
                +"<a href=
    http://www.baidu.com>baidu</a>"
                + "<img src=cid:image/></body></html>", true);
    FileSystemResource img = new FileSystemResource(new File("单.png"));
    messageHelper.addInline("image", img);
    //跟cid一致
    sender.send(mailMessage);
    System.out.println("邮件发送成功...");
    }
    }

    5、发送带附件的邮件

    importjava.io.File; 
    importjavax.mail.MessagingException;
    importjavax.mail.internet.MimeMessage;
    importorg.springframework.context.ApplicationContext;
    importorg.springframework.context.support.ClassPathXmlApplicationContext;
    importorg.springframework.core.io.FileSystemResource;
    importorg.springframework.mail.javamail.JavaMailSenderImpl;
    importorg.springframework.mail.javamail.MimeMessageHelper;

    public class SpringAttachedImageMail {

    public static voidmain(String[] args) throws MessagingException {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    JavaMailSenderImpl sender = (JavaMailSenderImpl) ctx.getBean("mailSender");
    MimeMessage mailMessage = sender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);
    messageHelper.setFrom("9197****1@qq.com");
    messageHelper.setTo("9197****1@qq.com");
    messageHelper.setSubject("测试邮件中嵌套图片!!");// true 表示启动HTML格式的邮件
    messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
                +"<a href=
    http://www.baidu.com>baidu</a>"
                + "<img src=cid:image/></body></html>", true);
    FileSystemResource img = new FileSystemResource(new File("单.png"));
    messageHelper.addAttachment("单.png", file);
    //添加到附件
    sender.send(mailMessage);
    System.out.println("邮件发送成功...");
    }
    }

     个人备份:

    import java.io.InputStream;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    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;
    import javax.mail.internet.MimeUtility;
    import javax.mail.util.ByteArrayDataSource;
    import com.sun.mail.util.MailSSLSocketFactory;
    
    public class MailUtil {
        /** 
         *  
         * 方法名: sendMail  
         * 描述: 发送邮件 
         * 创建人: zhangzhuo
         * 参数: @param subject 
         * 参数: @param toMail 
         * 参数: @param content 
         * 参数: @param files 
         * 参数: @return 
         * 返回类型: boolean 
         * @throws BaseException 
         */  
        public static boolean sendMail(String fromMail, String password, String subject, String toMail, String content,
                List<InputStream> listIs, List<String> listName) throws Exception {    
            boolean isFlag = false;
            String smtpFromMail = fromMail;//账号
            String pwd = password; //密码
            String host = "smtp.qq.com"; //端口
    
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            //QQ邮箱
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
    
            Session session = Session.getDefaultInstance(props);
            session.setDebug(false);    
    
            MimeMessage message = new MimeMessage(session);
            try {    
                message.setFrom(new InternetAddress(smtpFromMail));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
                message.setSubject(subject);
                message.addHeader("charset", "UTF-8");
    
                /*添加正文内容*/    
                Multipart multipart = new MimeMultipart();
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setText(content);
    
                //contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
                multipart.addBodyPart(contentPart);
    
                /*添加附件*/
                for (int i = 0; i < listIs.size(); i++) {
                    MimeBodyPart fileBody = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(listIs.get(i), "application/msexcel");
                    fileBody.setDataHandler(new DataHandler(source));
                    String fileName  = listName.get(i);
                    // 中文乱码问题  
                    fileBody.setFileName(MimeUtility.encodeText(fileName));
                    multipart.addBodyPart(fileBody);
                }
    
                message.setContent(multipart);
                message.setSentDate(new Date());
                message.saveChanges();
                Transport transport = session.getTransport("smtp");
    
                transport.connect(host, smtpFromMail, pwd);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                isFlag = true;
            } catch (Exception e) {
                e.printStackTrace();
                isFlag = false;
            }
            return isFlag;
        }
    }
  • 相关阅读:
    趣谈多线程
    使用application manifest file
    参加一个.NET培训后的若干笔记
    遍历sql server数据库的简单方法
    为什么对继承的方法签名检查这么严格?
    Serialize Dictionary to xml using DataContractSerializer
    如何在sql中查询xml字符串
    从PowerDesigner概念设计模型(CDM)中的3种实体关系说起
    using "code coverage coloring" to help debuging
    日常工作中用到过的PowerShell指令
  • 原文地址:https://www.cnblogs.com/laoyeye/p/6581205.html
Copyright © 2020-2023  润新知