Java-mail Send e-mail

1, call the tools emission Mail *

@SuppressWarnings(“null”)
private void getSendEmailStartus(RequestInfo requestInfo) throws Exception {
String account = xxxxx;// 登录账户
String password =xxxxxxx;// 登录密码
// 抄送者账号
String csz = xxxxx;
String requestid = requestInfo.getRequestid();
FormtableMain19 find = DB.conn().find(FormtableMain19.class, “REQUESTID=?”, requestid);
// 附件名称
String[] fileName = null;
// 附件地址
String[] fileSrc = null;
if (null != find) {
String[] fjsc = new String[] { “123456C1”, “123456C2”, “123456C3” };
if (fjsc.length > 0) {
fileSrc = new String[fjsc.length];
fileName = new String[fjsc.length];
for (int i = 0; i < fjsc.length; i++) {
Find2 = DB.conn EmailPDF () Find (EmailPDF.class, "fileuniqueidentifier =?", Fjsc [I]);.
FileName [I] = find2.getImagefilename ();
filesrc [I] = find2.getFilerealpath ();
}
}
IF (CustomUtil.isBlank (find.getYjll ())) {
the throw a RuntimeException new new ( "message can not be empty, requestId is:" + RequestID);
}
IF (CustomUtil.isBlank (find.getYxdz ())) {
the throw new RuntimeException ( "e-mail address can not be empty, requestId is:" + RequestID);
}
IF {(SendEmailUtil.isMailAddr (find.getYxdz ())!)
the throw new RuntimeException ( "email address entered is not valid, requestId is:" + RequestID);
}
new new SendEmailUtil (.) Send (Account, "XXX:" + find.getXm (), find.getYjll (), find.getYxdz () + "," + CSZ,
filesrc, Account, password, fileName) ;
}

}

Profile *

# Mail service configuration
email.host = xxxxx.xxx.163.com # domain people
email.prot = *** # port
email.protocol = imap # Agreement
#-mail account, password
devEmail.ACCOUNT = ******* *****
devEmail.PWSSWORD = *************

Mail Tools *

private static Logger logger = Logger.getLogger(SendEmailUtil.class);
private static byte[] ZIP_HEADER_1 = new byte[] { 80, 75, 3, 4 };
private static byte[] ZIP_HEADER_2 = new byte[] { 80, 75, 5, 6 };
static {
System.setProperty(“mail.mime.splitlongparameters”, “false”);
System.setProperty(“mail.mime.charset”, “UTF-8”);
}

public static Session initProperties(String account, String password) {
	Properties properties = new Properties();
	properties.setProperty("mail.transport.protocol", PropUtil.getStringCK("ecustom", "email.protocol"));
	properties.setProperty("mail.smtp.host", PropUtil.getStringCK("ecustom", "email.host"));
	properties.setProperty("mail.smtp.port", PropUtil.getStringCK("ecustom", "email.prot"));
	properties.put("mail.smtp.auth", "true");
	MailSSLSocketFactory mailSSLSocketFactory = null;
	try {
		mailSSLSocketFactory = new MailSSLSocketFactory();
		mailSSLSocketFactory.setTrustAllHosts(true);
	} catch (GeneralSecurityException e) {
		e.printStackTrace();
	}
	properties.put("mail.smtp.enable", "true");
	properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
	properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	properties.put("mail.smtp.socketFactory.fallback", "false");
	properties.put("mail.smtp.socketFactory.port", PropUtil.getStringCK("ecustom", "email.prot"));
	存在session问题:
	Session session = Session.getDefaultInstance(properties, new Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(account, password);
		}
	});
	第二种:
	Session session = Session.getInstance(properties, new Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(account, password);
		}
	});
	session.setDebug(true);
	return session;
}

Expand knowledge:

Problem solving,
the Session session = Session.getDefaultInstance (props, myauth );
changed
Session session = Session.getInstance (props, myauth );
can
I follow his method to replace the code in the method a bit, re-run, enter the first email account and password, successfully sent, a second input other email account and password, send a point, ok, successful.
Well, problem solved here, but do not understand Session.getDefaultInstance and Session.getInstance What difference does it make? And looking at the statistics, the results also found 553 anomalies encountered people who write a blog, is actually the title of his blog:
"JavaMail in Session.getDefaultInstance application",
is not it, so difficult to find, general is the name of the search problem, who will search this. If the poster can change the title of the problem, then I will not have to look so on the. But still would like to thank this man, he explains in detail why the method used Session.getDefaultInstance will appear when you enter other email account to log the second occurrence of abnormality in this post 553.
The following are this excerpt from this post:
http://muder2007.blog.163.com/blog/static/45933070200872025130613/

What getDefaultInstance?
As can be seen from the process flow, first from the cache if there are properties exist
if present, the default properties are loaded
If there is only load properties defined by the user,
so when a separate application for each user in order to create properties , or should call the getInstance,
unless you want to have a default properties allow users to use

Found the problem, because it will first go to memory and system files to look for properties, so no matter what I change the data in the page a few times, and in fact the same as when the system starts generating the session in the background, so MailUtil.sendTextMessage (mailSession , RptTaskMailConfig.Sender,
Receiver, null, mail_subject, mail_content, "GB2312", null); inconsistent session where the sender and the incoming sender, therefore the error, modify Session.getDefaultInstance (props, authentic); as Session.getInstance ( props, authentic); later, you can modify the message after sending the correct account number, password and other information .OK

Finally, add the difference session.getdefaultinstance and getinstance of:

If you want to use both accounts to send javamail, such as the use [email protected] 1 # send e-mail, use the Send [email protected] 2 #-mail, this time, you will need to create two objects simultaneously java.mail.Session . But if you are still using Session.getDefaultInstance create session objects, you will find that the second username: session [email protected] created and always like the first, this is why? Because, getDefaultInstance is truly a singleton, and, inside the username and password properties are final type can not be changed. So, you will find two email is sent by the [email protected] come. So this time you want to use javax.mail.Session.getInstance () method to create a session object.

/**
 * @Description: 发送邮件
 * @Title: send
 * @date 2019-10-08 17:12
 * @param @param sender发件人别名
 * @param @param subject邮件主题
 * @param @param content接收者列表,多个接收者之间用","隔开
 * @param @param receiverList :内容
 * @param @param fileSrc []附件地址
 * @return void 返回类型 fileName:[]附件名称 account: 发送者账户 password :发送者密码
 * @throws @return void
 * @param sender
 * @param subject
 * @param content
 * @param receiverList
 * @param fileSrc
 * @throws Exception 
 */
public void send(String sender, String subject, String content, String receiverList, String[] fileSrc,
		String account, String password, String[] fileName) throws Exception {

	Session session = initProperties(account, password);
	MimeMessage mimeMessage = new MimeMessage(session);
	mimeMessage.setFrom(new InternetAddress(account, sender));// 发件人,可以设置发件人的别名
	InternetAddress[] internetAddressTo = new InternetAddress().parse(receiverList);
	mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
	mimeMessage.setSubject(subject);
	mimeMessage.setSentDate(new Date());
	Multipart mainParth = new MimeMultipart();
	BodyPart html = new MimeBodyPart();
	html.setContent(content, "text/html; charset=UTF-8");
	mainParth.addBodyPart(html);
	MimeBodyPart bodyPart = new MimeBodyPart();
	if (fileSrc != null && fileSrc.length > 0) {
		logger.info("附件数量:" + fileSrc.length);
		URL url;
		for (int i = 0; i < fileSrc.length; i++) {
			String devAgreement =http;
			if (fileSrc[i].startsWith(devAgreement)) {
				logger.info("在线附件文件发送");
				bodyPart = new MimeBodyPart();
				url = new URL(fileSrc[i]);
				DataSource dataSource = new URLDataSource(url);
				DataHandler dataHandler = new DataHandler(dataSource);
				bodyPart.setDataHandler(dataHandler);
				mainParth.addBodyPart(bodyPart);
			} else {
				logger.info("附件文件发送含压缩文件");
				bodyPart = new MimeBodyPart();
				MimeBodyPart bodyPart2 = fileDecompression(bodyPart, fileSrc[i], fileName[i]);
				mainParth.addBodyPart(bodyPart2);
				logger.info("》》》退出");
			}

		}
	}
	logger.info("》》》内容进入");
	mimeMessage.setContent(mainParth);
	//mimeMessage.saveChanges();
	logger.info("》》》发射");
	Transport.send(mimeMessage);
	logger.info("邮件发送结束");
}

/**
 * @Description:解压服务器文件 不同服务器文件解压读取未解决
 * @Title: fileDecompression
 * @date 2019-11-01
 * @param @param string 参数
 * @return void 返回类型
 * @throws @return void
 * @param string
 * @throws IOException
 * @throws MessagingException
 */
private MimeBodyPart fileDecompression(MimeBodyPart bodyPart, String filePath, String fileName)
		throws IOException, MessagingException {
	logger.info("文件地址:" + filePath);
	logger.info("文件名称:" + fileName);
	File file = new File(filePath);
	if (!file.exists()) {
		fileError(file);
	}
	boolean archiveFile = isArchiveFile(file);
	if (archiveFile) {//zip压缩包
		logger.info("压缩包邮件解析发送");
		DataSource ds = new FileDataSource(file);
		bodyPart.setDataHandler(new DataHandler(ds));
		bodyPart.setFileName(MimeUtility.encodeWord(fileName, "UTF-8", "Q"));
		logger.info("压缩包邮件解析结束");
		return bodyPart;
	} else {// 文件
		logger.info("文件发送");
		DataSource ds = new FileDataSource(file);
		bodyPart.setDataHandler(new DataHandler(ds));
		bodyPart.setFileName(MimeUtility.encodeWord(fileName, "UTF-8", "Q"));
		return bodyPart;
	}
}

/**
 * @Description: 抛出异常
 * @Title: fileError
 * @date 2019-11-05 17:48
 * @param @param file 参数
 * @return void 返回类型
 * @throws @return void
 * @param file
 */
private void fileError(File file) {
	throw new RuntimeException("文件路径不正确");
}

/**
 * 判断文件是否为一个压缩文件
 * 
 * @param file
 * @return
 */
public static boolean isArchiveFile(File file) {

	if (file == null) {
		return false;
	}

	if (file.isDirectory()) {
		return false;
	}

	boolean isArchive = false;
	InputStream input = null;
	try {
		input = new FileInputStream(file);
		byte[] buffer = new byte[4];
		int length = input.read(buffer, 0, 4);
		if (length == 4) {
			isArchive = (Arrays.equals(ZIP_HEADER_1, buffer)) || (Arrays.equals(ZIP_HEADER_2, buffer));
		}
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (input != null) {
			try {
				input.close();
			} catch (IOException e) {
			}
		}
	}

	return isArchive;
}

/**
 * 
 * @param mailString 待判断的mail邮件地址
 * @return boolean 是否匹配成功
 */
public static boolean isMailAddr(String mailString) {
	String pattenString = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
	Pattern pattern = Pattern.compile(pattenString);
	Matcher matcher = pattern.matcher(mailString);
	return matcher.matches();
}

To Learn More:

multipart/form-data:

1, may be submitted to the ordinary key-value pairs, you can submit (multiple) file pairs.

2, Content-Type HTTP specification does not contain this type can only be used in a POST submission, belonging http client (browser, java httpclient) extension

3, usually form in the browser, or http client (java httpclient) is used.

application/octet-stream:

1, only submitted to binary, and can submit a binary, if the submitted documents, only to submit a document, receiving background only one parameter, but only stream (or byte array)

2, belonging to the HTTP specification of one of the Content-Type

3, rarely used

application/x-www-form-urlencoded

1, does not belong to http content-type specification, commonly used browser form submission, data organization format: name1 = value1 & name2 = value2, post time will be placed http body, get when displayed in the address bar.

2, all keys and values, will be urlencoded, please see urlencoder

Converted into a byte stream extracting archive email array introduced into the vessel *

/**
* 根据文件路径获取ZIP字节流。
* @param zipFilePath
* @return
* @throws IOException
*/
public static byte[] getBytesByZip(String zipFilePath) throws IOException{
InputStream inputStream;
byte[] fileByte = null;
ZipFile zipFile = null;
try{
zipFile = new ZipFile(zipFilePath);
Enumeration<?> entries = zipFile.getEntries();
while (entries.hasMoreElements()){
ZipEntry entry = (ZipEntry)entries.nextElement();
inputStream = zipFile.getInputStream(entry);
fileByte = inputStreamToByte(inputStream);
inputStream.close();
}
} finally {
if (zipFile != null) {
zipFile.close();
}
}
return fileByte;
}

/**
 * InputStream文件流转换成字节数组。
 * @param in	文件流
 * @return
 * @throws IOException
 */
public static byte[] inputStreamToByte(InputStream in)
		throws IOException{
	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	byte[] data = new byte[1024];
	int count = -1;
	while((count = in.read(data, 0, 1024)) != -1) {
		outStream.write(data, 0, count);
	}
	outStream.close();
	data = null;
	return outStream.toByteArray();
}

Send attachments in different ways:

/ **
* E-mail and by byte [] stream or send email attachments base64 encoded string
* @param Notice
* @return void
* /
public void sendEmailByFlow (Notice Notice) throws Exception {
Boolean = sessionDebug to false;
the InternetAddress [] = address null;
the SimpleDateFormat the SimpleDateFormat SDF new new = ( "the mM-dd-YYYY HH: mm: SS");
the try {

		SiteConfig  config = new SiteConfig();                    	//配置信息
		String mailServer = config.getSendEmailSmtp();              //服务器地址
		String mailAuth = config.getMailSmtpAuth();                 //验证
		String mailAddress = config.getSendEmailAddress();          //邮箱
		String mailUser = config.getSendEmailAddress();             //用户名
		String mailPassword = config.getSendEmailPassword();        //密码
		String mailSmtpPort = config.getMailSmtpPort();             //端口
		
		Properties props = System.getProperties();
		props.put("mail.smtp.host", mailServer);
		props.put("mail.smtp.auth", mailAuth);

		Session mailSession = Session.getDefaultInstance(props, null);
		mailSession.setDebug(sessionDebug);

		Message msg = new MimeMessage(mailSession);
		msg.setFrom(new InternetAddress(mailAddress));
		if (notice.getToAddress() != null && !"".equals(notice.getToAddress())) {
			address = InternetAddress.parse(notice.getToAddress(), false);
			for (InternetAddress addr:address) {
				if (this.isEmail(addr.getAddress()) == false) {
					log.info(sdf.format(new Date() + notice.getScene() + addr.getAddress() + "地址格式不正确。"));
				}
			}
			msg.setRecipients(Message.RecipientType.TO, address);
		}
		if (notice.getCcAddress() != null && !"".equals(notice.getCcAddress())) {
			address = InternetAddress.parse(notice.getCcAddress(), false);
			for (InternetAddress addr:address) {
				if (this.isEmail(addr.getAddress()) == false) {
					log.info(sdf.format(new Date() + notice.getScene() + addr.getAddress() + "地址格式不正确。"));
				}
			}
			msg.setRecipients(Message.RecipientType.CC, address);
		}
		if (notice.getBccAddress() != null && !"".equals(notice.getBccAddress())) {
			address = InternetAddress.parse(notice.getBccAddress(), false);
			for (InternetAddress addr:address) {
				if (this.isEmail(addr.getAddress()) == false) {
					log.info(sdf.format(new Date() + notice.getScene() + addr.getAddress() + "地址格式不正确。"));
				}
			}
			msg.setRecipients(Message.RecipientType.BCC, address);
		}
		
        String message = notice.getContent();
		msg.setSubject(notice.getTitle());
		msg.setSentDate(new Date());

		msg.setText(message);
		Multipart mm = new MimeMultipart();
		BodyPart mdp = new MimeBodyPart();                 //新建一个存放信件内容的BodyPart对象
		mdp.setContent(message, "text/html;charset=UTF-8");
		mm.addBodyPart(mdp);                               //将含有信件内容的BodyPart加入到MimeMultipart对象中

		String[] fname = notice.getAttachFileName();
		byte[] data = null;
        String[] file64Str = notice.getFile64Str();
        if (file64Str != null && file64Str.length > 0) {
    		BASE64Decoder base = new BASE64Decoder();
			for (int i=0; i<fname.length; i++) {
				data = base.decodeBuffer(file64Str[i]);
				mdp = new MimeBodyPart();
				DataSource obj = new ByteArrayDataSource(data, "application/octet-stream");
				DataHandler dh = new DataHandler(obj);
				mdp.setDataHandler(dh);
				mdp.setFileName(MimeUtility.encodeWord(fname[i],"UTF-8","Q")); 
				mdp.setHeader("content-id", fname[i]); 
				mm.addBodyPart(mdp);
			}
        } else {
        	data = notice.getFileFlow();
			mdp = new MimeBodyPart();
			DataSource obj = new ByteArrayDataSource(data, "application/octet-stream");
			DataHandler dh = new DataHandler(obj);
			mdp.setDataHandler(dh);
			mdp.setFileName(MimeUtility.encodeWord(fname[0],"UTF-8","Q")); 
			mdp.setHeader("content-id", fname[0]); 
			mm.addBodyPart(mdp);
        }


		msg.setContent(mm);
		msg.saveChanges();

		Transport transport = mailSession.getTransport("smtp");
		transport.connect(mailServer, Integer.parseInt(mailSmtpPort), mailUser, mailPassword);
		transport.sendMessage(msg, msg.getAllRecipients());
		transport.close();
		

	} catch (MessagingException e) {
		e.printStackTrace();
		log.error(sdf.format(new Date() + notice.getScene() + "异常错误,邮件发送失败。"));
		throw e;
	}
}

private boolean isEmail(String str) {
	String regex = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
	return match(regex, str);
}

private boolean match(String regex, String str) {
	Pattern pattern = Pattern.compile(regex);
	Matcher matcher = pattern.matcher(str);
	return matcher.matches();
}

/**
 *  根据byte数组,生成文件。
 * @param filePath	目标文件路径
 * @return
 * @throws IOException 
 */
public static void toRealFile(byte[] bfile, String filePath)
		throws IOException {
	BufferedOutputStream bos = null;
	FileOutputStream fos = null;
	File file = null;
	try {
		file = new File(filePath);
		fos = new FileOutputStream(file);
		bos = new BufferedOutputStream(fos);
		bos.write(bfile);
	} finally {
		if (bos != null) {
			bos.close();
		}
		if (fos != null) {
			fos.close();
		}
	}
}
Published 26 original articles · won praise 0 · Views 718

Guess you like

Origin blog.csdn.net/YHM_MM/article/details/102888643