1. 程式人生 > >Java:發郵件

Java:發郵件

java 郵件 發送

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!!!");
	}
}




Java:發郵件