1、使用JavaMail发送邮件
1.1 添加依赖
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.3</version> </dependency>
讯享网
1.2 简单邮件发送
讯享网@Test() public void testSend() throws Exception { // 连接邮件服务器的参数配置 Properties props = new Properties(); // 设置用户的认证方式 props.setProperty("mail.smtp.auth", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); // 创建定义整个应用程序所需的环境信息的 Session 对象 Session session = Session.getInstance(props,new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(name, pwd); } }); // 创建消息对象 MimeMessage message = new MimeMessage(session); // 邮件消息头 message.setFrom(new InternetAddress(name)); // 发件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人 message.setSubject("邮件测试1"); message.setText("Hello, java mail!"); // 发送邮件 Transport.send(message); }
2、使用Spring的JavaMailSenderImpl发送邮件
2.1 添加依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.14.RELEASE</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.3</version> </dependency>
2.2 简单邮件发送
讯享网@Test public void testSend2() throws MessagingException { JavaMailSenderImpl sendService = new JavaMailSenderImpl(); sendService.setHost(host); sendService.setPort(port); sendService.setUsername(name); sendService.setPassword(pwd); MimeMessage msg = sendService.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8"); helper.setTo(to); helper.setFrom(name); helper.setSubject("邮件测试2"); helper.setText("Hello, spring!", true); sendService.send(msg); }
3、使用Apache commons-email发送邮件
3.1 添加依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.3</version> </dependency>
3.2 简单邮件发送
讯享网@Test public void testSend3() throws EmailException { Email email = new SimpleEmail(); email.setHostName(host); email.setSmtpPort(port); email.setAuthenticator(new DefaultAuthenticator(name, pwd)); email.setCharset("UTF-8"); email.setFrom(name); email.addTo(to); email.setSubject("测试邮件3"); email.setMsg("Hello, commons-email!"); email.send(); }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/54289.html