MAIL メールの受信(POP)・Javaの小技、サンプル、ニュースなどを紹介していきます。みんなで参考にしてください。

Ads by Google


上記の広告は1ヶ月以上更新のないブログに表示されています。
新しい記事を書く事で広告が消せます。

MAIL メールの受信(POP)


メールの受信は以下のサンプルを参考にしてください。
JavaMail1.3ベースです。ライブラリは以下のURLからダウンロードできます。
http://java.sun.com/products/javamail/index.jsp
JAFでダウンロード可能な activation.jar が追加ライブラリとして必要です。
http://java.sun.com/products/javabeans/jaf/downloads/index.html




try {
//接続の作成
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);

Store store = session.getStore("pop3");
store.connect(mailServer, mailUser, mailPasswd);
Folder folder = store.getFolder(mbox);
if (folder == null) {
System.out.println("folder is null");
System.exit(1);
}

if (folder.isOpen()) {
System.out.println("folder is already open");
return;
}
folder.open(Folder.READ_WRITE);

//全メールを読み込む
Message[] msgs = null;
msgs = folder.getMessages();
if (msgs.length > 0)
System.out.println("mail num="+msgs.length);
for (int i = 0; i < msgs.length; i++) {
//メールの解析
storeMessage(msgs[i]);
}

folder.close(true);
}
catch (Exception e) {
e.printStackTrace();
}

/**
* メッセージの解析を実行する
*
* @param msg メールメッセージ
*/
protected boolean storeMessage(Message msg) throws MessagingException, IOException, SQLException
{
MailProperty mail = new MailProperty();
boolean ret = storePart(msg, mail);
if (ret)
msg.setFlag(Flags.Flag.DELETED, true);
return ret;
}

/**
* メールの解析を行い、値をMailクラスに設定する。
*
* @param p メールの部品
* @param mail メールクラス
*/
protected boolean storePart(Part p, AbstractMailProperty mail) throws IOException, SQLException, MessagingException
{
try {

if (p instanceof Message) {
Message m = (Message)p;

//FROM
javax.mail.Address[] adr = m.getFrom();
mail.address = adr[0].toString();

//Subject
String sub = m.getSubject();
mail.subject = sub;
if (sub == null)
mail.subject = new String("");
// 送信日時をセット
mail.sentDate = m.getSentDate();

// 受信日時をセット
mail.receivedDate = m.getReceivedDate();
if (mail.receivedDate == null)
mail.receivedDate = new java.util.Date();
}

Object o = p.getContent();

if (o instanceof String) {
if (p.isMimeType("text/html")) {
String url = o.toString();
mail.stringPart(url);
return true;
}
String url = o.toString();
mail.stringPart(url);
return true;
}
else if (o instanceof Multipart) {
//マルチパート
Multipart mp = (Multipart)o;
int count = mp.getCount();

for (int i = 0; i < count; i++) {
if (storePart(mp.getBodyPart(i), mail) == false)
return false;
}
return true;
}
else if (o instanceof InputStream) {
//添付ファイル
InputStream is = (InputStream)o;
String fname = p.getFileName();
mail.fileNames.add(fname);

mail.inputStreamPart(fname, is);

return true;
}
else if (o instanceof Message) {
Message m = (Message)o;
return storePart(m, mail);
}
System.out.println("content="+o.getClass().getName()+" not found!!");
return false;

}
catch (Exception e) {
e.printStackTrace();
return false;
}
}


Copyright © Javaテクニカルサンプル集 All Rights Reserved.
FC2ブログ 一戸建て
相互リンクRANGER