Showing posts with label Mail. Show all posts
Showing posts with label Mail. Show all posts

Sunday, November 16, 2008

Get mail from gmail using pop of javamail

javamail官方论坛中一个用pop协议从gmail中获取邮件的例子,需要在gmail中开启pop功能。

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

import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;

import com.sun.mail.pop3.POP3SSLStore;

public class GmailUtilities {

private Session session = null;
private Store store = null;
private String username, password;
private Folder folder;

public GmailUtilities() {

}

public void setUserPass(String username, String password) {
this.username = username;
this.password = password;
}

public void connect() throws Exception {

String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

Properties pop3Props = new Properties();

pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");

URLName url = new URLName("pop3", "pop.gmail.com", 995, "", username, password);

session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();

}

public void openFolder(String folderName) throws Exception {

// Open the Folder
folder = store.getDefaultFolder();

folder = folder.getFolder(folderName);

if (folder == null) {
throw new Exception("Invalid folder");
}

// try to open read/write and if that fails try read-only
try {

folder.open(Folder.READ_WRITE);

} catch (MessagingException ex) {

folder.open(Folder.READ_ONLY);

}
}

public void closeFolder() throws Exception {
folder.close(false);
}

public int getMessageCount() throws Exception {
return folder.getMessageCount();
}

public int getNewMessageCount() throws Exception {
return folder.getNewMessageCount();
}

public void disconnect() throws Exception {
store.close();
}

public void printMessage(int messageNo) throws Exception {
System.out.println("Getting message number: " + messageNo);

Message m = null;

try {
m = folder.getMessage(messageNo);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
}
}

public void printAllMessageEnvelopes() throws Exception {

// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();

// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);

for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs[i]);
}

}

public void printAllMessages() throws Exception {

// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();

// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);

for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpPart(msgs[i]);
}

}

public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message) p);

String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}

/*
* Using isMimeType to determine the content type avoids fetching the
* actual content data until we need it.
*/
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
System.out.println((String) p.getContent());
} else {

// just a separator
pr("---------------------------");

}
}

public static void dumpEnvelope(Message m) throws Exception {
pr(" ");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
}

// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("TO: " + a[j].toString());
}
}

// SUBJECT
pr("SUBJECT: " + m.getSubject());

// DATE
Date d = m.getSentDate();
pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

}

static String indentStr = " ";
static int level = 0;

/**
* Print a, possibly indented, string.
*/
public static void pr(String s) {

System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}

}
Usage:

public class GmailPop {

public static void main(String[] args) {

try {

GmailUtilities gmail = new GmailUtilities();
gmail.setUserPass("test.yu@gmail.com", "****password****");
gmail.connect();
gmail.openFolder("INBOX");

int i = 0;
int totalMessages = gmail.getMessageCount();
int newMessages = gmail.getNewMessageCount();

System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");

do {
i++;
gmail.printMessage(i);
} while (i < 10);

// Uncomment the below line to print the body of the message.
// Remember it will eat-up your bandwidth if you have 100's of
// messages.
// gmail.printAllMessageEnvelopes();
// gmail.printAllMessages();

} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}

Sunday, September 02, 2007

Rails ActionMailer send mail using GMail

在config/environment.rb文件末添加ActionMailer配置,在插件目录里加入Net::SMTP补丁。


require 'smtp_tls'
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.server_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "localhost",
:authentication => :plain,
:user_name => "test.yu@gmail.com",
:password => "********"
}

vendor/plugins/action_mailer_tls/init.rb

require_dependency 'smtp_tls'

vendor/plugins/action_mailer_tls/lib/smtp_tls.rb

require "openssl"
require "net/smtp"
Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
check_auth_args user, secret, authtype if user or secret

sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout

check_response(critical { recv_response() })
do_helo(helodomain)

raise 'openssl library not installed' unless defined?(OpenSSL)
starttls
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
do_helo(helodomain)

authenticate user, secret, authtype if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
@socket.close if not @started and @socket and not @socket.closed?
@socket = nil
end
end

def do_helo(helodomain)
begin
if @esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
end

def starttls
getok('STARTTLS')
end

def quit
begin
getok('QUIT')
rescue EOFError
end
end
end

reference:http://blog.pomozov.info/posts/how-to-send-actionmailer-mails-to-gmailcom.html

Tuesday, May 15, 2007

用Ruby程序接收邮件


require 'net/pop'

pop = Net::POP3.new('pop3.126.com')
pop.start('test', 'password') # (1)
if pop.mails.empty?
puts 'No mail.'
else
i = 0
# pop.each_mail do |m| # or "pop.mails.each ..." # (2)
# File.open("#{i}", 'w') do |f|
# f.write m.pop
# end
# m.delete
# i += 1
# end
pop.mails.each do |m|
File.open("mail", 'a') do |f|
f.write m.pop
end
end
puts "#{pop.mails.size} mails popped."
end
pop.finish

Linux fetchmail 使用实例

fetchmail 工具需要一个名为 .fetchmailrc 的配置文件才能正常工作。 这个文件中包含了服务器信息, 以及登录使用的凭据。 由于这个文件包含敏感内容, 建议将其设置为只有属主所有, 使用下面的命令:

$> chmod 600 .fetchmailrc

下面的 .fetchmailrc 提供了一个将某一用户的信箱通过 POP 下载到本地的例子。

poll pop3.163.com proto pop3:
username "test", with password "password", is "yu" here;

更多的资料可参考官方手册,另此软件作者Eric Steven Raymond是个开源项目牛人,出过一篇有影响力的文章《大教堂与集市》。

telnet 收发邮件

Initiative - est's Blog
收邮件 开始 运行 cmd 回车,OK, Let's go!

telnet 202.115.22.199 110
USER electronixtar
PASS 我的密码啦

可以看到统计了,接下来

STAT 可以查看统计

LIST 看所有信件

RETR 1 收第一封啦。可惜邮件是 Base64 编码的。不过习惯就对了,以后我们应聘的时候可以吹会第三门外语Base64呢,哇咔咔

TOP 1 10 收最前面的1封的前10行内容

DELE 1 删除第一封

QUIT 断开连接,闪人鸟~

发邮件 开始 运行 cmd 回车,OK, Let's go on!

telnet 202.115.22.199 25

EHLO Multiversal 偶的电脑名字,双方协商呢,看来蛮友好的嘛。服务器返回:
250-mail.dormforce.net
250-AUTH CRAM-MD5 PLAIN LOGIN DIGEST-MD5 NTLM
250-SIZE 10485760
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-PIPELINING
250-ETRN
250-DSN
250 HELP
可能列出了一些命令吧,继续,

AUTH LOGIN 用一般登陆模式。从上面的服务器返回可以看到居然支持 AUTH CRAM-MD5 PLAIN LOGIN DIGEST-MD5 NTLM,爽啊,支持这么多 ^_^
服务器返回,
AUTH LOGIN
334 VXNlcm5hbWU6
服务器问你用户名呢,不过是 Username: Base64编码后的字符
ZWxlY3Ryb25peHRhcg==
偶的用户名 Base64编码后,看来以后如果用 telnet 收邮件,得背用户名的Base64写法啊
334 UGFzc3dvcmQ6
回答是你的密码 Base64 加密后的字符串,这里偶就不敢写了。
235 2.0.0 Authentication successful

然后开始写邮件啦。注意准备好Base64翻译器:

MAIL FROM: 发件人吧
250 2.1.0 Sender ok

RCPT TO: 收件人吧
250 2.1.5 Recipient ok (remote)

DATA
然后就是正文了,符合 MIME 规范就可以了。贴一个例子:

From: electronixtar@dormforce.net
To: electronicstar@dormforce.net
Subject: Hello From telnet
Mime-Version: 1.0
Content-Type: text/plain

Hello!

.

最后结束,打一个回车,一个 句号 . 英文半角的,然后再一个回车,写信完毕!

QUIT 断开连接,闪人。

btw,今天抓包发现,DreamMail发邮件速度快的原因是采用了异步读取,真是NB啊~