欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java mail发送邮件

程序员文章站 2022-05-24 16:41:13
...

业务场景

       在公司内部的linux主机上,通过shell调用java application来连接公司的邮件服务器,进行邮件发送

 

实现方式

       1>通过shell读取ini文件中的配置参数,并export成系统环境变量,然后调用java程序

       2>java程序里读取环境变量进行邮件发送

 

mail.ini

 

MAIL_HOST="192.168.1.21"
MAIL_FROM="system@xxx.com"
MAIL_TO_USERS="user1@xxx.com"
MAIL_CC_USERS="user2@xxx.com,user3@xxx.com"
MAIL_ATTACH_PATH="/application/attach"

 

mail.sh

 

#!/bin/sh

while read line;do
    eval "$line"
done < mail.ini

export MAIL_HOST=$MAIL_HOST
export MAIL_FROM=$MAIL_FROM

export MAIL_TO=$MAIL_TO_USERS
export MAIL_CC=$MAIL_CC_USERS
export MAIL_SUBJECT="hello"
export MAIL_CONTENT="good morning!"
export MAIL_ATTACHMENT=$MAIL_ATTACH_PATH

java -jar mailer.jar
RETCODE=$?
if [ $RETCODE -eq 0 ]; 
then 
exit 0
else
exit 2
fi

 

Mailer.java

 

import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMultipart;

public class Mailer {
	
	private String mailHost;
	private String mailFrom;
	private String mailTo;
	private String mailCc;
	private String mailSubject;
	private String mailContent;
	private String mailAttachmentPath;
	private String mailAttachmentFile;
	private final String MAIL_CONTENT="text/html;charset=shift_jis";
	private static int returnCode;
	
	public Mailer(){
		this.mailHost = System.getenv("MAIL_HOST");
		this.mailFrom = System.getenv("MAIL_FROM");
		this.mailTo = System.getenv("MAIL_TO");
		this.mailCc = System.getenv("MAIL_CC");
		this.mailSubject = System.getenv("MAIL_SUBJECT");
		this.mailContent = System.getenv("MAIL_CONTENT");
		this.mailAttachmentPath = System.getenv("MAIL_ATTACHMENT");
	}
	
	public void sendMail() throws MessagingException{
		Properties prop = new Properties();
		prop.setProperty("mail.host",this.mailHost);
		prop.setProperty("mail.transport.protocol","smtp");
		prop.setProperty("mail.smtp.auth","false");
		
		Session session = Session.getInstance(prop);
		
		Transport transport = null;
		
		try {
			transport = session.getTransport();
			transport.connect();
			if(transport.isConnected()){
				System.out.println("Connected successfully!");
			}
			
			Message message = null;
			this.mailAttachmentFile = this.getAttachment();
			if(!"".equals(this.mailAttachmentFile)){
				message =  this.createAttachMail(session);
			} else {
				message = this.createSimpleMail(session);
			}
			
			transport.sendMessage(message,message.getAllRecipients());
		} catch (NoSuchProviderException e) {
			throw e;
		} catch (MessagingException e) {
			throw e;
		} finally {
			try {
				if(transport.isConnected()){
					transport.close();
				}
				System.out.println("Disconnected successfully!");
			} catch (MessagingException e) {
				throw e;
			}
		}
	}
	
	private MimeMessage createSimpleMail(Session session) throws AddressException, MessagingException{
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(mailFrom));
		message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(mailTo));
		if(mailCc != null && !"".equals(mailCc)){
			message.setRecipients(Message.RecipientType.CC,InternetAddress.parse(mailCc));
		}
		message.setSubject(mailSubject);
		message.setContent(mailContent, MAIL_CONTENT);
		return message;
	}
	
	private MimeMessage createAttachMail(Session session) throws AddressException, MessagingException{
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(mailFrom));
		message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(mailTo));
		if(mailCc != null && !"".equals(mailCc)){
			message.setRecipients(Message.RecipientType.CC,InternetAddress.parse(mailCc));
		}
		message.setSubject(mailSubject);
		
		MimeBodyPart text = new MimeBodyPart();
		text.setContent(mailContent, MAIL_CONTENT);
		
		MimeBodyPart attach = new MimeBodyPart();
		DataHandler dh = new DataHandler(new FileDataSource(this.mailAttachmentFile));
		attach.setDataHandler(dh);
		attach.setFileName(dh.getName());
		
		MimeMultipart mp = new MimeMultipart();
		mp.addBodyPart(text);
		mp.addBodyPart(attach);
		mp.setSubType("mixed");
		message.setContent(mp);
		message.saveChanges();
		
		return message;
	}
	
	private String getAttachment(){
		if(this.mailAttachmentPath != null && !"".equals(this.mailAttachmentPath)){		
			File file = new File(this.mailAttachmentPath);
			File[] fileArray = file.listFiles();
			
			if(1 == fileArray.length){
				return fileArray[0].getAbsolutePath();
			}
			
			if( 0 == fileArray.length){
				return "";
			}
			
			long newTime = 0;
			int newIndex = 0;
			for(int i=0; i < fileArray.length; i++){
				long curTime = fileArray[i].lastModified();
				if(curTime > newTime){
					newTime = curTime;
					newIndex = i;
				}
			}
			
			return fileArray[newIndex].getAbsolutePath();
		}
		return "";
	}
	
	public static void main(String[] args){
		try {
			Mailer mailer = new Mailer();
			mailer.sendMail();
			returnCode = 0;
		} catch (Exception e) {
			returnCode = 1;
		} finally {
			System.exit(returnCode);
		}
	}
}