如何快速实现java发邮件

这是基于springboot+maven 的简单封装发送邮件

下面是整体架构 :

首先引进依赖,pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>maildemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>maildemo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

mail.properties:

这里的mail.host 也可以是smtp.163.com 等其他邮件服务,mail.username 是邮箱帐户,例如 xxxxxxxxx@qq.com,mail.password 是 stmp 的16位口令

#
mail.host=smtp.qq.com
mail.port=465
mail.username=
mail.password=
mail.debug=true
mail.ssl=true
mail.auth=true


 MailData.java:

package com.example.demo.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MailData {
	@Value("${mail.host}")
	private String host;
	@Value("${mail.port:25}")
	private String port;
	@Value("${mail.protocol:smtp}")
	private String protocol = "smtp";
	@Value("${mail.auth:false}")
	private Boolean auth = true;
	@Value("${mail.debug:false}")
	private Boolean debug = true;
	@Value("${mail.username}")
	private String username;
	@Value("${mail.password}")
	private String password;
	@Value("${mail.mail:#{mailData.username}}")
	private String mail;
	@Value("${mail.name:#{mailData.username}}")
	private String name;
	@Value("${mail.ssl:false}")
	private Boolean ssl=false;
	

	private Session session = null;
	private Transport transport = null;

	public Properties getPropertise() {
		Properties prop = new Properties();
		prop.setProperty("mail.smtp.host", host);
		prop.setProperty("mail.smtp.port", port);
		prop.setProperty("mail.transport.protocol", protocol);
		prop.setProperty("mail.smtp.auth", auth.toString());
		if (ssl) {
			prop.setProperty("mail.smtp.ssl.enable", "true");
		}
		return prop;
	}

	public Session getSession() {
		if (session!=null) {
			return session;
		}
		
		if (!ssl) {
			session = Session.getInstance(getPropertise(), new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});
		}
		else {
			/*session = Session.getDefaultInstance(getPropertise(), new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});*/
			session = Session.getInstance(getPropertise(), new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});
			
		}
		// 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
		session.setDebug(debug);
		return session;
	}
	
	public Transport geTransport() throws MessagingException {
		if (transport!=null) {
			return transport;
		}
		transport=getSession().getTransport();
		transport.connect(username, password);
		return transport;
	}
	
	public Transport geTransport(Session session) throws MessagingException {
		if (transport!=null) {
			return transport;
		}
		transport=session.getTransport();
		transport.connect(username, password);
		return transport;
	}
	
	public void sendMsg(MimeMessage msg) {
		try {
			getTransport().send(msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
		transport=null;
	}
	
	public InternetAddress getFrom() throws UnsupportedEncodingException {
		InternetAddress from=new InternetAddress(mail,name,"utf-8");
		return from;
	}
}

MailMsgSingle.java 

package com.example.demo.mail;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

import org.springframework.beans.factory.annotation.Autowired;


import lombok.Data;
import lombok.experimental.Accessors;
@Accessors(chain=true)
@Data
public class MailMsgSingle {
	//MimeMessage message=new MimeMessage(message);
	@Autowired
	private MailData mailData;
	private MimeMessage message;
	private String toMail;
	private String toName;
	
	private String subject;
	private String contetnText;
	private String attachFile;
	private List<String> attachFiles=new ArrayList<>();
	
	private Multipart multipart=new MimeMultipart();
	
	
	public MimeMessage getMimeMessage() throws UnsupportedEncodingException, MessagingException {
		if (message!=null) {
			return message;
		}
		message=new MimeMessage(mailData.getSession());
		//message.setFrom(new InternetAddress("", "", ""));;
		return message;
	}
	
	public void sendMsg() throws MessagingException, IOException {
		InternetAddress [] addresses=InternetAddress.parse(toMail);
		if (toName!=null) {
			if (toName.contains(",")) {
				String []tos=toName.split(",");
				if (tos.length!=addresses.length) {
					throw new RuntimeException("tomail.length != toname.length");
				}
				for (int i = 0; i < tos.length; i++) {
					addresses[i].setPersonal(tos[i], "utf-8");
				}
			}
			else {
				for (InternetAddress internetAddress : addresses) {
					internetAddress.setPersonal(toName, "utf-8");
				}
			}
		}
		MimeMessage msg=getMimeMessage();
		msg.addRecipients(RecipientType.TO, addresses);
		msg.setFrom(mailData.getFrom());
		if (subject!=null) {
			msg.setSubject(subject, "utf-8");
		}
		else {
			subject=contetnText.substring(0,6);
			msg.setSubject(subject, "utf-8");
		}
		
		MimeBodyPart text=new MimeBodyPart();
		text.setContent(contetnText, "text/html;charset=utf-8");
		multipart.addBodyPart(text);
		if (attachFile==null&&attachFiles.size()==0) {
			//multipart.addBodyPart(text);
		}
		else {
			if (attachFiles.size()==0) {
				//MimeBodyPart file=getFileBodyPart(attachFile);
				MimeBodyPart file=new MimeBodyPart();
				file.attachFile(attachFile);
				multipart.addBodyPart(file);
			}
			else {
				if (attachFile!=null&&!"".equals(attachFile)) {
					attachFiles.add(attachFile);
				}
				for (String str : attachFiles) {
					//MimeBodyPart file=getFileBodyPart(str);
					MimeBodyPart file=new MimeBodyPart();
					if (str!=null&&!"".equals(str.trim())) {
						file.attachFile(str);
						multipart.addBodyPart(file);
					}
					
				}
			}
			
		}
		msg.setContent(multipart);
		mailData.sendMsg(msg);
 	}
	

	
	
	
	
}

BeanConfig.java

package com.example.demo.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.example.demo.mail.MailData;
import com.example.demo.mail.MailMsgSingle;


@Configuration
@PropertySource({"classpath:mail.properties"})
public class BeanConfig {

	@Bean
	public MailData mailData() {
		return new MailData();
	}
	@Bean
	public MailMsgSingle mailMsgSingle() {
		return new MailMsgSingle();
	}
}

MaildemoApplication .java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MaildemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(MaildemoApplication.class, args);
	}
}

MaildemoApplicationTests.java 最后写一个测试: 

package com.example.demo;

import java.io.IOException;

import javax.mail.MessagingException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.demo.mail.MailMsgSingle;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MaildemoApplicationTests {

	@Autowired
	MailMsgSingle msg;
	
	@Test
	public void contextLoads() {
	}
	@Test
	public void testSendMail() throws MessagingException, IOException {
		msg.setToMail("xxxxxxxxx@xxx.com").setContetnText("This is a test for sending mail").
		setSubject("this is a test").setAttachFile("e:/a/tt.txt").setToName("Hi girl").sendMsg();
	}

}

然后就可以接收到了:

支持的可以点个赞。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烟火里的尘埃.

有问题可以留言

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值