zoukankan      html  css  js  c++  java
  • 使用 Java 发送邮件

    在我们的应用程序中有时需要给用户发送邮件,例如激活邮件、通知邮件等等。那么如何使用 Java 来给用户发送邮件呢?

    • 使用 java 代码发送邮件

    • 使用工具类发送邮件

    • 使用Spring进行整合发送邮件

    • 发送带附件的邮件


    一.使用 Java 代码发送邮件

    第一步:导入依赖坐标

    <!-- Javamail -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.4</version>
    </dependency>

    第二步:编写 Java 代码发送邮件

    /**
     * java程序发送邮件
     * @author Mr.song
     * @date 2019/05/24 16:17
     */
    public class JavaMail {
        public static void main(String[] args) throws Exception {
            //1.配置发送邮件的属性
            Properties properties = new Properties();
            properties.setProperty("mail.smtp.host", "localhost"); //设置协议主机
            properties.setProperty("mail.smtp.auth", "true"); //设置smtp是否需要认证
            //2.根据属性获得一个会话
            Session session = Session.getInstance(properties);
            //3.设置会话是debug模式(会打印更多相关信息)
            session.setDebug(true);
            //4.创建邮件主题信息对象
            MimeMessage message = new MimeMessage(session);
            //5.设置发件人
            message.setFrom(new InternetAddress("dintalk@sh.com"));
            //6.设置邮件主题
            message.setSubject("我的第一份java邮件");
            //7.设置邮件正文
            message.setText("第一份邮件发送成功了,哈哈");
            //8.设置收件人: TO-发送    CC-抄送   BCC-密送
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("talkdin@sh.com"));
            //9.获取发送器对象:提供指定的协议
            Transport transport = session.getTransport("smtp");
            //10.设置发件人的信息
            transport.connect("localhost", "dintalk", "123456");
            //11.发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            //12.关闭资源
            transport.close();
        }
    }

    二.使用工具类发送邮件

    第一步:导入依赖坐标(同 上)

    第二步:抽取工具类

    /**
     * @author Mr.song
     * @date 2019/05/24 16:53
     */
    public class MailUtil {
        /**
         * 工具类发送邮件的方法里,发件邮箱的信息是固定的
         * @param map : 收件地址和发送类型 (地址作 key)
         * @param subject : 邮件的主题
         * @param content : 邮件的正文
         * @throws MessagingException
         */
        public static void sendMail(Map<String,String>map,String subject,String content) 
            throws MessagingException {
            //1.配置发送邮件的属性
            Properties properties = new Properties();
            properties.setProperty("mail.smtp.host","localhost"); //设置协议主机
            properties.setProperty("mail.smtp.auth","true"); //设置smtp是否需要认证
            //2.根据属性获得一个会话
            Session session = Session.getInstance(properties);
            //3.设置会话是debug模式(会打印更多相关信息,生产环境可设为false)
            session.setDebug(true);
            //4.创建邮件主题信息对象
            MimeMessage message = new MimeMessage(session);
            //5.设置发件人
            message.setFrom(new InternetAddress("dintalk@sh.com"));
            //6.设置邮件主题
            message.setSubject(subject);
            //7.设置邮件正文
            message.setText(content);
            //8.设置收件人: TO-发送    CC-抄送   BCC-密送
            for (Map.Entry<String, String> me : map.entrySet()) {
                String email = me.getKey(); //邮件地址
                String type = me.getValue(); //邮件类型
                if ("to".equalsIgnoreCase(type)){
                    //发送
                    message.setRecipient(Message.RecipientType.TO,new InternetAddress(email));
                }else if ("cc".equalsIgnoreCase(type)){
                    //抄送
                    message.setRecipient(Message.RecipientType.CC,new InternetAddress(email));
                }else if ("bcc".equalsIgnoreCase(type)){
                    //密送
                    message.setRecipient(Message.RecipientType.BCC,new InternetAddress(email));
                }
            }
            //9.获取发送器对象:提供指定的协议
            Transport transport = session.getTransport("smtp");
            //10.设置发件人的信息
            transport.connect("localhost","dintalk","123456");
            //11.发送邮件
            transport.sendMessage(message,message.getAllRecipients());
            //12.关闭资源
            transport.close();
        }
    }

    第三步:发送邮件

    /**
     * 使用工具类发送邮件
     * @author Mr.song
     * @date 2019/05/24 16:47
     */
    public class UtilMail {
        public static void main(String[] args) throws Exception{
            Map<String,String> map = new HashMap<>();
            map.put("din@sh.com","to");
            map.put("talk@sh.com","cc");
            map.put("talkdin@sh.com","bcc");
            MailUtil.sendMail(map,"我的第二封邮件","使用工具类发送邮件....");
        }
    }

    三.整合Spring进行邮件发送

    第一步:导入依赖坐标

    <!-- Javamail -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.4</version>
    </dependency>
    <!--整合spring坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.0.4.RELEASE</version>
    </dependency>

    第二步:编写发件方邮箱配置文件(mail.properties)

    #设置发件方邮箱地址
    mail.from=dintalk@sh.com
    #设置协议主机
    mail.host=localhost
    #设置发件方用户名
    mail.username=dintalk
    #设置发件方密码
    mail.password=123456
    #设置邮件编码格式
    mail.encoding=UTF-8
    #设置邮件发送协议
    mail.protocol=smtp

    第三步:编写mail的Spring配置文件( applicationContext-mail.xml )

    <?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:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/context
                       http://www.springframework.org/schema/context/spring-context.xsd">
        <!-- 1.指定引入其他资源文件.properties文件 -->
        <context:property-placeholder location="classpath:mail.properties"/>
        <!-- 2.配置简单邮件消息对象 -->
        <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
            <!-- 此时我们只需要注入发件箱名称即可。不要注入主题,正文,收件箱等不固定的信息 -->
            <property name="from" value="${mail.from}"></property>
        </bean>
    
        <!-- 3.配置邮件发送器 -->
        <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
            <property name="host" value="${mail.host}"></property>
            <property name="username" value="${mail.username}"></property>
            <property name="password" value="${mail.password}"></property>
            <property name="defaultEncoding" value="${mail.encoding}"></property>
            <property name="protocol" value="${mail.protocol}"></property>
            <property name="javaMailProperties">
                <props>
                    <!-- 是否需要验证 -->
                    <prop key="mail.smtp.auth">true</prop>
                    <!-- 是否需要debug的信息 -->
                    <prop key="mail.debug">true</prop>
                    <!-- 设置发送超时时间,以秒为单位。0为永不超时 -->
                    <prop key="mail.smtp.timeout">0</prop>
                </props>
            </property>
        </bean>
    </beans>

    第四步:发送邮件

    /**
     * 整合Spring的邮件发送
     * @author Mr.song
     * @date 2019/05/24 17:07
     */
    public class SpringMail {
    
        public static void main(String[] args) throws MessagingException {
            //1.获取Spring容器
            ApplicationContext ac = new ClassPathXmlApplicationContext
                ("classpath:applicationContext-mail.xml");
            //2.获取消息对象
            SimpleMailMessage mailMessage = (SimpleMailMessage) ac.getBean("mailMessage");
            //3.设置邮件的主题
            mailMessage.setSubject("Spring整合javamail");
            //4.设置邮件的内容,和收件人信息
            mailMessage.setText("Spring整合javamail成功");
            mailMessage.setTo("din@sh.com","talk@sh.com");
            mailMessage.setCc("talkdin@sh.com");
            //5.获取邮件发送对象
            JavaMailSenderImpl mailSender = (JavaMailSenderImpl) ac.getBean("mailSender");
            //6.发送邮件
            mailSender.send(mailMessage);
        }
    }

    四.发送带附件的邮件(在整合Spring的基础上)

    编写带附件的邮件

    /**
     * 发送带附件的邮件
     * @author Mr.song
     * @date 2019/05/24 17:35
     */
    public class AttachmentMail {
        public static void main(String[] args) throws MessagingException {
            //1.获取spring的容器
            ApplicationContext ac = new ClassPathXmlApplicationContext
                    ("classpath:applicationContext-mail.xml");
            //2.获取发送器对象(spring提供的)
            JavaMailSenderImpl sender = (JavaMailSenderImpl) ac.getBean("mailSender");
            //3.获取MimeMessage
            MimeMessage mailMessage = sender.createMimeMessage();
            //4.创建spring提供的复杂邮件的帮助对象
            MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
            //5.设置发件人邮箱
            helper.setFrom("dintalk@sh.com");
            //6.设置邮件的收件人
            helper.setTo("din@sh.com");
            //7.设置邮件的主题
            helper.setSubject("带有附件和图片的邮件");
            //8.设置邮件的正文
            helper.setText("<html><head></head><body><h1>这是一封带有附件和图片的邮件</h1><img src=cid:image></body></html>", true);
            //9.设置图片
            FileSystemResource resource = new FileSystemResource(new File("C:\Users\Administrator\Desktop\1.png"));
            //10.使用图片替换cid (cid是规定的,只能用cid)
            helper.addInline("image", resource);
            //11.设置附件
            helper.addAttachment("1.png", resource);
            //12.发送邮件
            sender.send(mailMessage);
        }
    }

    关注微信公众号,随时随地学习

  • 相关阅读:
    PHP开发者的MySQL错误
    shell编程技术和实例《linux0.01内核分析与操作系统设计》
    函数问题1 init_EMUX
    sizeof问题
    C语言读书心得
    《深入浅出MFC》读书感受
    计算机专业学习多年的苦恼
    一个完整的字符设备驱动程序导读
    学习书籍选择
    鼠标滑动、文本添加(倒计时)
  • 原文地址:https://www.cnblogs.com/dintalk/p/10933279.html
Copyright © 2011-2022 走看看