使用 Java 发送邮件

2020-12-03 08:44

阅读:713

YPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

标签:文件   编写   java   mes   resource   code   png   date   如何   

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

  • 使用 java 代码发送邮件

  • 使用工具类发送邮件

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

  • 发送带附件的邮件


 

一.使用 Java 代码发送邮件

第一步:导入依赖坐标


dependency>
    groupId>javax.mailgroupId>
    artifactId>mailartifactId>
    version>1.4.4version>
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(Mapmap,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 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 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进行邮件发送

第一步:导入依赖坐标


dependency>
    groupId>javax.mailgroupId>
    artifactId>mailartifactId>
    version>1.4.4version>
dependency>

dependency>
    groupId>org.springframeworkgroupId>
    artifactId>spring-context-supportartifactId>
    version>5.0.4.RELEASEversion>
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">
    
    context:property-placeholder location="classpath:mail.properties"/>
    
    bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
        
        property name="from" value="${mail.from}">property>
    bean>

    
    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">trueprop>
                
                prop key="mail.debug">trueprop>
                
                prop key="mail.smtp.timeout">0prop>
            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("

这是一封带有附件和图片的邮件

", 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); } }

 

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

技术图片

 

使用 Java 发送邮件

标签:文件   编写   java   mes   resource   code   png   date   如何   

原文地址:https://www.cnblogs.com/dintalk/p/10933279.html


评论


亲,登录后才可以留言!