javamail发邮件

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail 
{

	public static final String HOST = "";
	public static final String FROM = "";
	public static final String USERNAME = "";
	public static final String PASSWORD = "";

	public static final boolean DEBUG = false;

	public static void mail(String to, String title, String mailBody) throws AddressException, MessagingException   {
		// create some properties and get the default Session
		Properties props = new Properties();
		props.put("mail.smtp.host", HOST);
		Session session = Session.getInstance(props, null);
		session.setDebug(DEBUG);

		// create a message
		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(FROM));
		InternetAddress[] address = { new InternetAddress(to) };
		msg.setRecipients(Message.RecipientType.TO, address);
		msg.setSubject(title);
		msg.setSentDate(new Date());
		// create and fill the first message part
		MimeBodyPart mbp = new MimeBodyPart();
		mbp.setText(mailBody, "utf-8");
		// create the Multipart and its parts to it		
		Multipart mp = new MimeMultipart();
				
		mp.addBodyPart(mbp);
		// add the Multipart to the message
		msg.setContent(mp);

		// send the message
		Transport transport = session.getTransport("smtp");
		transport.connect((String) props.get("mail.smtp.host"), USERNAME,
				PASSWORD);
		transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

	}
	
}

你可能感兴趣的:(javamail)