SSL方式发送mail

随意了,以下是3段简单代码,测试数据采取gmail方式:

package com.mail;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SSLMail {
	
	private static String session_sender = "";
	
	private static String session_password = "";

	public static int sendMail(String smtp,String smtp_port,String sender,String password,String subject, String body,
			String mailto, String mailFrom) {
		int flag = 0;
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", smtp);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", smtp_port);
		props.put("mail.smtp.socketFactory.port", smtp_port);
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");
		session_sender = sender;
		session_password = password;
		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(session_sender, session_password);
					}
				});

		MimeMessage message = new MimeMessage(session);
		try {
			InternetAddress address = null;
			try {
				address = new InternetAddress(sender, mailFrom);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			message.setFrom(address);
			message.setSubject(subject);
			message.setContent(body, "text/html; charset=utf-8");
			if (mailto.indexOf(',') > 0)
				message.setRecipients(Message.RecipientType.TO, InternetAddress
						.parse(mailto));
			else
				message.setRecipient(Message.RecipientType.TO,
						new InternetAddress(mailto));

			Transport.send(message);
			System.out.println("sender:" + sender + ",recipients:" + mailto
					+ ",mailFrom:" + mailFrom);
		} catch (AddressException e) {
			e.printStackTrace();
			flag = 1;
		} catch (MessagingException e) {
			e.printStackTrace();
			flag = 2;
		}
		return flag;
	}

	public static void main(String args[]) throws Exception {
		System.out.println(SSLMail.sendMail("smtp.gmail.com","465","[email protected]","ooxx","aaa", "ccc",
				"[email protected]", "sendername"));

	}

}

 

package com.mail;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 使用Gmail发送邮件
 * 
 * @author Winter Lau
 */
public class GmailSender {

	public static void main(String[] args) throws AddressException,
			MessagingException {
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		// Get a Properties object
		Properties props = System.getProperties();
		props.setProperty("mail.smtp.host", "smtp.gmail.com");
		props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.port", "465");
		props.setProperty("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.auth", "true");
		final String username = "[email protected]";
		final String password = "13785211300";
		Session session = Session.getDefaultInstance(props,
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		// -- Create a new message --
		Message msg = new MimeMessage(session);

		// -- Set the FROM and TO fields --
		msg.setFrom(new InternetAddress(username));
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
				"[email protected]", false));
		msg.setSubject("Hello");
		msg.setText("How are you");
		msg.setSentDate(new Date());
		Transport.send(msg);

		System.out.println("Message sent.");
	}
}

 

 

package com.mail;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Properties;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

/**
 * 用于收取Gmail邮件
 * 
 * @author Winter Lau
 */
public class GmailFetch {

	public static void main(String argv[]) throws Exception {

		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

		// Get a Properties object
		Properties props = System.getProperties();
		props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
		props.setProperty("mail.pop3.socketFactory.fallback", "false");
		props.setProperty("mail.pop3.port", "995");
		props.setProperty("mail.pop3.socketFactory.port", "995");

		// 以下步骤跟一般的JavaMail操作相同
		Session session = Session.getDefaultInstance(props, null);

		// 请将红色部分对应替换成你的邮箱帐号和密码
		URLName urln = new URLName("pop3", "pop.gmail.com", 995, null,
				"[email protected]", "13785211300");
		Store store = session.getStore(urln);
		Folder inbox = null;
		try {
			store.connect();
			inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			FetchProfile profile = new FetchProfile();
			profile.add(FetchProfile.Item.ENVELOPE);
			Message[] messages = inbox.getMessages();
			inbox.fetch(messages, profile);
			System.out.println("收件箱的邮件数:" + messages.length);
			for (int i = 0; i < messages.length; i++) {
				// 邮件发送者
				String from = decodeText(messages[i].getFrom()[0].toString());
				InternetAddress ia = new InternetAddress(from);
				System.out.println("FROM:" + ia.getPersonal() + '('
						+ ia.getAddress() + ')');
				// 邮件标题
				System.out.println("TITLE:" + messages[i].getSubject());
				// 邮件大小
				System.out.println("SIZE:" + messages[i].getSize());
				// 邮件发送时间
				System.out.println("DATE:" + messages[i].getSentDate());
			}
		} finally {
			try {
				inbox.close(false);
			} catch (Exception e) {
			}
			try {
				store.close();
			} catch (Exception e) {
			}
		}
	}

	protected static String decodeText(String text)
			throws UnsupportedEncodingException {
		if (text == null)
			return null;
		if (text.startsWith("=?GB") || text.startsWith("=?gb"))
			text = MimeUtility.decodeText(text);
		else
			text = new String(text.getBytes("ISO8859_1"));
		return text;
	}

}
 

你可能感兴趣的:(java)