JavaMail 收发邮件示例

MailService.java

package cn.bisoft.java.mail;

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

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailService {

	/**
	 * @param args
	 * @throws MessagingException
	 * @throws IOException
	 */
	public static void main(String[] args) throws MessagingException, IOException {
		new MailService().send();
		new MailService().receive();
	}

	public void send() throws MessagingException {
		Properties props = new Properties();
		props.setProperty("mail.debug", "true");
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");

		props.setProperty("mail.host", "smtp.sina.com");
		props.setProperty("mail.user", "amos_tl");
		props.setProperty("mail.from", "[email protected]");

		Session session = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("amos_tl", "257111221");
			}
		});

		Message message = new MimeMessage(session);
		message.setSubject("主题");
		message.setRecipients(RecipientType.TO, InternetAddress.parse("[email protected], [email protected]"));
		message.setContent("<font color='red'>你好!</font>", "text/html;charset=utf-8");

		Transport.send(message);
	}

	public void receive() throws MessagingException, IOException {
		Properties props = new Properties();
		props.setProperty("mail.debug", "true");
		props.setProperty("mail.pop3.auth", "true");
		props.setProperty("mail.transport.protocol", "pop3");

		Session session = Session.getInstance(props);
		session.setDebug(true);

		Store store = session.getStore("pop3");

		store.connect("pop3.sohu.com", "amos_tl", "257111221");

		Folder folder = store.getDefaultFolder();
		folder = folder.getFolder("INBOX");
		folder.open(Folder.READ_ONLY);

		Message[] messages = folder.getMessages();

		int index = 0;
		for (Message m : messages) {
			System.out.println((++index) + "\n" + m.getContent());
		}
	}

}
 

你可能感兴趣的:(java,html)