java 发邮件,有监控需要发送邮件到op通知很简单 直接调用

SendMail2.sendMail("[email protected]","报警信息")


package com.stevezong.sendMail;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendMail2 {
	
	private static final String MAIL_HOST = "smtp.exmail.qq.com";
	private static final int MAIL_TIMEOUT = 3000;
	private static final boolean MAIL_AUTH = true;
	private static final String AUTH_USER_ADDRESS = "邮箱";
	private static final String AUTH_USER_PASSWORD = "邮箱密码";
	private static final String AUTH_USER_NICKNAME = "监控看门狗";

	//receiver 收件人
	//mailInfo 邮件信息
	public static void sendMail(String receiver, String mailInfo) throws IOException, MessagingException  {
		Properties serverProperties = new Properties();
		serverProperties.put("mail.smtp.host", MAIL_HOST);
		serverProperties.put("mail.smtp.auth", MAIL_AUTH);
		serverProperties.put("mail.smtp.timeout", MAIL_TIMEOUT);
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(AUTH_USER_ADDRESS, AUTH_USER_PASSWORD);
			}
		};
		Session session = Session.getInstance(serverProperties, authenticator);
		Message mailMsg = new MimeMessage(session);
		//邮件标题
		mailMsg.setSubject("XXX异常");
		mailMsg.setFrom(
				new InternetAddress(MimeUtility.encodeText(AUTH_USER_NICKNAME) + "<" + AUTH_USER_ADDRESS + ">"));
		mailMsg.setRecipient(RecipientType.TO, new InternetAddress(receiver));
		mailMsg.setRecipient(RecipientType.CC, new InternetAddress("抄送人邮箱"));
		Multipart mailContent = new MimeMultipart();
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setText(mailInfo+"time:"+System.currentTimeMillis());
		mailContent.addBodyPart(contentPart);
		mailMsg.setContent(mailContent);
		Transport.send(mailMsg);
		System.out.println("sendMailSucceed!!!");
	}
}