惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
NISL@THU
NISL@THU
E
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
K
Kaspersky official blog
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
S
Schneier on Security
G
GRAHAM CLULEY
The Hacker News
The Hacker News
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
T
Tor Project blog
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
爱范儿
爱范儿
P
Privacy International News Feed
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
S
Securelist
G
Google Developers Blog
The Last Watchdog
The Last Watchdog
Google Online Security Blog
Google Online Security Blog
美团技术团队
F
Fortinet All Blogs
小众软件
小众软件
Recorded Future
Recorded Future
V
Visual Studio Blog
B
Blog RSS Feed
H
Help Net Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
Martin Fowler
Martin Fowler
Latest news
Latest news
Spread Privacy
Spread Privacy
H
Heimdal Security Blog

博客园 - 不明飞行物

磨刀不误砍柴工-打造超级Symbian开发环境 Symbian OS 开发初级手册 (8) 多线程 Symbian OS 开发初级手册 (7) Descriptors - 不明飞行物 Symbian OS 开发初级手册 (6) CleanupStack and Two-phase Symbian OS 开发初级手册 5 - Leave Symbian OS 开发初级手册 (4) mmp, pkg 文件 和 makesis 工具 Symbian OS 开发初级手册 (3)GUI程序中的4个基本类 Symbian OS 开发初级手册 (2)基本数据类型 Symbian OS 开发初级手册 (1) Introduction Tapestry4在提交前判断checkbox是否没有一个被选中 - 不明飞行物 - 博客园 恢复windows的引导程序 在页面中插入Windows Media Player播放器 - 不明飞行物 Java中Set的深入研究 - 不明飞行物 - 博客园 Hibernate和Spring的延迟加载和DAO模式 用spring管理hibernate事务时,lzay="true"不能用的解决方法 java中List和Set对象的互换 Tapestry4.0中取得页面request - 不明飞行物 - 博客园 Logout in tapesty4.0 - 不明飞行物 validators里自定义错误信息 - 不明飞行物 - 博客园
利用JavaMail收/发Gmail邮件(SSL)
不明飞行物 · 2006-04-06 · via 博客园 - 不明飞行物

Gmail目前已经启用了POP3和SMTP服务,具体情况请看 http://www.javayou.com/showlog.jspe?log_id=490

与其他邮箱不同的是Gmail提供的POP3和SMTP是使用安全套接字层SSL的,因此常规的JavaMail程序是无法收发邮件的,下面是使用JavaMail如何收取Gmail邮件以及发送邮件的代码:

1. 邮件收取

package lius.javamail.ssl;

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Properties;
import javax.mail.*;
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,
    "[邮箱帐号]", "[邮箱密码]");
  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;
 }

}

2. 发送邮件

package lius.javamail.ssl;

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 = "[邮箱帐号]";
  final String password = "[邮箱密码]";
  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 + "@mo168.com"));
  msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse("[收件人地址]",false));
  msg.setSubject("Hello");
  msg.setText("How are you");
  msg.setSentDate(new Date());
  Transport.send(msg);
  
  System.out.println("Message sent.");
 }
}

关于邮件的解析请看 http://www.javayou.com/showlog.jspe?log_id=372
更多关于javamail的文章 http://www.javayou.com/main.jspe?query=javamail