使用技術及框架:Spring Boot + RabbitMQ
- pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--rabbitMq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--郵件系統(tǒng)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--第三方庫整合上下文-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
- application.yml
spring:
mail:
host: smtp.qq.com
port: 25
username: xxxx@qq.com
password: xxxx # 郵箱授權密碼
personal: xxx # 發(fā)件人別名
protocol: smtp
default-encoding: UTF-8
rabbitmq:
host: 你的rabbit服務器地址
port: 5672
username: username
password: password
virtual-host: /
connection-timeout: 60000
3.郵件發(fā)送核心類
@Component
public class MailBase {
@Autowired
JavaMailSender javaMailSender;
/**
* TODO: 發(fā)送郵件
* @param from 發(fā)件人
* @param personal 發(fā)件人昵稱
* @param to 收件人
* @param subject 主題
* @param content 內容
* @param fileUrl 附件
* @param fileName 附件名稱
*/
public void sendSimpleMail(String from,String personal,String to,String subject,String content,String fileUrl,String fileName){
MimeMessage message = null;
try {
message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from,personal);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (!fileUrl.equals("") && !fileName.equals("")){
FileSystemResource fileSystemResource=new FileSystemResource(new File(fileUrl));
helper.addAttachment(fileName,fileSystemResource);
}
javaMailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
- rabbit消息隊列消息推送端
/**
* 這里有兩種方案扮碧,一種是按我下面給出的代碼直接CP就可以吉执,另一種是
* @Component
* public class XXXSender(名字可以自行定義){}
*/
@Component("mailSenders")
public class MailSender {
private final Logger logger = LoggerFactory.getLogger(MailSender.class);
@Autowired
AmqpTemplate amqpTemplate;
@Value("${spring.mail.username}")
private String from;
@Value("${spring.mail.personal}")
private String personal;
/**
* TODO: 將郵件信息內容推送至消息隊列
* @param to 收件人
* @param subject 主題
* @param content 內容
* @param fileUrl 附件
* @param fileName 附件名稱
* @return
*/
public String send(String to,String subject,String content,String fileUrl,String fileName){
logger.info("郵件發(fā)送時間:"+new Date())
//TODO: 封裝郵件消息
BasePage mail = new BasePage();
mail.put("from",from);
mail.put("personal",personal);
mail.put("to",to);
mail.put("subject",subject);
mail.put("content",content);
mail.put("fileUrl",fileUrl);
mail.put("fileName",fileName);
amqpTemplate.convertAndSend("mailSev",mail);
return "已成功推送至郵件服務隊列";
}
}
- rabbit消息隊列消息接收處理端
@Component
@RabbitListener(queues = "mailSev")
public class MailReceiver {
private final Logger logger = LoggerFactory.getLogger(MailSender.class);
@Resource
MailBase mailBase;
@RabbitHandler
public void process(BasePage mail) {
// TODO 開始處理隊列中的內容·推送至郵件服務器進行發(fā)送
mailBase.sendSimpleMail(mail.getString("from"),mail.getString("personal"),
mail.getString("to"),mail.getString("subject"),
mail.getString("content"),mail.getString("fileUrl"),mail.getString("fileName"));
logger.info("郵件推送時間:" + new Date());
}
}
- BasePage Map的封裝類丐黄,如果感覺麻煩可以將4/5中BasePage對象替換為Map對象
public class BasePage extends HashMap implements Map{
private static final long serialVersionUID = 1L;
Map map = null;
HttpServletRequest request;
@SuppressWarnings("unchecked")
public BasePage(HttpServletRequest request){
this.request = request;
Map properties = request.getParameterMap();
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
returnMap.put(name, value);
}
map = returnMap;
}
public BasePage() {
map = new HashMap();
}
@Override
public Object get(Object key) {
Object obj = null;
if(map.get(key) instanceof Object[]) {
Object[] arr = (Object[])map.get(key);
obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
} else {
obj = map.get(key);
}
return obj;
}
public String getString(Object key) {
return (String)get(key);
}
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
return map.put(key, value);
}
@Override
public Object remove(Object key) {
return map.remove(key);
}
public void clear() {
map.clear();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public Set entrySet() {
return map.entrySet();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Set keySet() {
return map.keySet();
}
@SuppressWarnings("unchecked")
public void putAll(Map t) {
map.putAll(t);
}
public int size() {
return map.size();
}
public Collection values() {
return map.values();
}
public String parsePage(){
StringBuffer sb = new StringBuffer();
Iterator<String> iteratorSet = this.keySet().iterator();
while (iteratorSet.hasNext()){
String key = iteratorSet.next();
sb.append(key).append("=")
.append(this.get(key)).append("&");
}
if (sb.length() > 0) sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}
- 調用
@Autowired
MailSender mailSenders;
mailSenders.send("test@qq.com","測試郵件","<h2>測試郵件內容</h2>","D:\\test.pdf","測試.pdf");