javamail使用小记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javamail使用小记相关的知识,希望对你有一定的参考价值。
/**
*
发送邮件主要有Properties(发送邮件的各种属性服务器地址,端口,用户名密码等),Authenticator(验证)这两个构建一个Session,Message设置一个邮件,然后Transport类send
*/
package com.util;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
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.MimeUtility;
/**
* @author wqf
*
*/
public class EmailSendTools {
private final static String _EMAIL_ACCOUNT = "[email protected]";
private final static String _EMAIL_PASSWORD = "XXX";
private final static String _SMTP_HOST = "smtp.qq.com";
private final static String _SMTP_PORT = "465";
private final static String _POP3_HOST = "pop.qq.com";
private final static String _POP3_PORT = "995";
/**
* @param args
*/
public static void main(String[] args) {
// sendEmail(_EMAIL_ACCOUNT, "test", "test");
receiveMail();
}
public static void receiveMail() throws SendEmailException{
try {
Store store = getSession(false).getStore();
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] msgs = folder.getMessages(1,20);
int count = msgs.length;
for (int i = 0; i < count; i++) {
System.out.println("发送人:" + decodeText(msgs[i].getFrom()[0].toString()));
System.out.println("主题:" + msgs[i].getSubject().toString());
}
} catch (NoSuchProviderException e) {
throw new SendEmailException("链接邮件失败" + e.getMessage(), e);
} catch (MessagingException e) {
throw new SendEmailException("读取收件箱失败:" + e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new SendEmailException("邮件解析失败:" + e.getMessage(), e);
}
}
private static String decodeText(String text)
throws UnsupportedEncodingException{
if (text == null)
return null;
if (text.startsWith("=?GB") || text.startsWith("=?gb") || text.startsWith("=?UTF") ||text.startsWith("=?utf"))
text = MimeUtility.decodeText(text);
else
text = new String(text.getBytes("ISO8859_1"));
return text;
}
/**
*
* @param from
* @param to
* @param title
* @param emsg
* @return boolean
* @throws SendEmailException
*/
public static boolean sendEmail(String to, String title, String emsg) throws SendEmailException {
try {
Session session = getSession(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(_EMAIL_ACCOUNT));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(title);
message.setText(emsg);
message.saveChanges();
Transport.send(message);
} catch (MessagingException e) {
throw new SendEmailException("邮件发送失败:" + e.getMessage(), e);
}
return true;
}
private static Properties getProp(boolean send) {
// Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties prop = new Properties();
if (send) {
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.host", _SMTP_HOST);
prop.setProperty("mail.smtp.auth", "true");
prop.setProperty("mail.smtp.port", _SMTP_PORT);
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.port", _SMTP_PORT);
} else {
prop.setProperty("mail.store.protocol", "pop3");
prop.setProperty("mail.pop3.host", _POP3_HOST);
prop.setProperty("mail.pop3.port", _POP3_PORT);
prop.setProperty("mail.pop3.auth", "true");
prop.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.pop3.socketFactory.fallback", "false");
prop.setProperty("mail.pop3.socketFactory.port", _POP3_PORT);
}
return prop;
}
private static Session getSession(boolean send) {
Session session = Session.getDefaultInstance(getProp(send), getAut());
// session.setDebug(true);
return session;
}
private static Authenticator getAut() {
Authenticator aut = new MyAuthenricator(_EMAIL_ACCOUNT, _EMAIL_PASSWORD);
return aut;
}
private static class SendEmailException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public SendEmailException() {
super();
}
@SuppressWarnings("unused")
public SendEmailException(String msg) {
super(msg);
}
@SuppressWarnings("unused")
public SendEmailException(Throwable cause) {
super(cause);
}
public SendEmailException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* 客户端程序自己实现Authenticator子类用于用户认证
*/
static class MyAuthenricator extends Authenticator {
String user = null;
String pass = "";
public MyAuthenricator(String user, String pass) {
this.user = user;
this.pass = pass;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
}
}
以上是关于javamail使用小记的主要内容,如果未能解决你的问题,请参考以下文章