您的位置:首页 > 编程语言 > Java开发

怎么样使用JavaMail发送和接收邮件

2011-11-06 14:15 453 查看
JavaMail收发邮件的步骤



<!--[if !supportLists]-->1、 <!--[endif]-->发邮件

<!--[if !supportLists]-->1) <!--[endif]-->获取Session

<!--[if !supportLists]-->i) <!--[endif]-->实行一个Authenticator类的子类,实行里面的public PasswordAuthentication getPasswordAuthentication()方法

<!--[if !supportLists]-->ii) <!--[endif]-->New一个上面类的实例,设置用户名和密码

<!--[if !supportLists]-->iii) <!--[endif]-->New一个Properties对象,设置mail.smtp.host and mail.smtp.auth属性

<!--[if !supportLists]-->iv) <!--[endif]-->同过Session的静态方法,获取一个Session实例

<!--[if !supportLists]-->2) <!--[endif]-->生成Message

<!--[if !supportLists]-->i) <!--[endif]-->没有附件的邮件

第一步:new一个MimeMessage实例(根据Session)

第二步:给Message实例设置subject、text属性

<!--[if !supportLists]-->ii) <!--[endif]-->有附件的邮件

第一步:根据Session new一个MimeMessage实例(Message)

第二步:设置Message subject属性

第三步:new一个MimeBodyPart实例 和 Mulipart(MimeMulipart)实例

第四步:给MimeBodyPart实例设置邮件文本内容

第五步:将MimeBodyPart实例,添加到Mulipart实例



第六步:根据附件数循环:

New MimeBodyPart实例

获取FileDatasource

将FileDatasource设置到MimeBodyPart

设置MimeBodyPart的文件名

将MimeBodyPart添加到 Mulipart

第七步:将Mulipart设置成MimeMessage的内容

<!--[if !supportLists]-->3) <!--[endif]-->发送邮件

<!--[if !supportLists]-->i) <!--[endif]-->设置Message的fromAddress,toAddress,ccAddress,bccAddress

<!--[if !supportLists]-->ii) <!--[endif]-->Transport发送邮件

<!--[if !supportLists]-->4) <!--[endif]-->

<!--[if !supportLists]-->2、 <!--[endif]-->收邮件

<!--[if !supportLists]-->1) <!--[endif]-->new Properties实例,设置mail.pop3.host 的值

<!--[if !supportLists]-->2) <!--[endif]-->获取Session实例

<!--[if !supportLists]-->3) <!--[endif]-->根据Session,获取Store实例

<!--[if !supportLists]-->4) <!--[endif]-->连接store

<!--[if !supportLists]-->5) <!--[endif]-->获取Index文件夹

<!--[if !supportLists]-->6) <!--[endif]-->打开文件夹

<!--[if !supportLists]-->7) <!--[endif]-->获取文件夹里面所有Message

<!--[if !supportLists]-->8) <!--[endif]-->用FetchProfile优化Message的查找

FetchProfile profile = new FetchProfile();

profile.add(FetchProfile.Item.ENVELOPE);

profile.add(FetchProfile.Item.FLAGS);

profile.add("X-Mailer");

inbox.fetch(msg, profile);

<!--[if !supportLists]-->9) <!--[endif]-->判断Message的MimeType类型如果是text/*类型,直接可以从Message从获取邮件from 地址、标题和内容,否则执行下面的步骤

<!--[if !supportLists]-->10) <!--[endif]-->从Message中获取Multipart

<!--[if !supportLists]-->11) <!--[endif]-->遍历Multipart中的BodyPart

<!--[if !supportLists]-->12) <!--[endif]-->判断bodyPart的Disposition是否是Part.ATTACHMENT

<!--[if !supportLists]-->13) <!--[endif]-->如果不是,直接获取bodyPart里面的content

<!--[if !supportLists]-->14) <!--[endif]-->否则获取bodyPart的文件名和文件流(inputstream),将流写入本地文件,实现附件的下载

<!--[if !supportLists]-->3、 <!--[endif]-->

样例代码如下:

UserAuthentication.java

package cn.com.javaweb.mail;

import javax.mail.Authenticator;

import javax.mail.PasswordAuthentication;

public class UserAuthentication extends Authenticator {

private String userName;

private String password;

public void setPassword(String password){

this.password = password;

}

public void setUserName(String userName){

this.userName = userName;

}

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName, password);

}

}

SendMailTest.java

package cn.com.javaweb.mail;

import java.io.IOException;

import javax.mail.internet.MimeMultipart;

import javax.mail.Multipart;

import java.io.FileReader;

import java.util.Properties;

import java.io.FileInputStream;

import javax.mail.Session;

import javax.mail.Authenticator;

import javax.mail.internet.MimeMessage;

import javax.mail.PasswordAuthentication;

import javax.mail.Message;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import java.util.Vector;

import java.util.Enumeration;

import javax.activation.FileDataSource;

import javax.activation.DataHandler;

import javax.mail.Transport;

import javax.mail.*;

public class SendMailTest {

public SendMailTest() {

}

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

String smtpServer = "192.168.1.245";

String userName = "user2";

String password = "yyaccp";

String fromAddress = "user1@mailserver";

String toAddress = "user2@mailserver";

String subject = "邮件标题";

String content = "邮件内容";

String attachFile1 = "d:/temp/test.txt";

String attachFile2 = "d:/temp/test2.txt";

SendMailTest sendMail = new SendMailTest();

Session session = sendMail.getSession(smtpServer, userName, password);

if(session != null){

String[] files = {attachFile1, attachFile2};

//Message msg = sendMail.getMessage(session, subject, content, files);

Message msg = sendMail.getMessage(session, subject, content);

if(msg != null){

//发送源地址

msg.setFrom(new InternetAddress(fromAddress));

//发送目的地址

InternetAddress[] tos = InternetAddress.parse(toAddress);

msg.setRecipients(Message.RecipientType.TO, tos);

//抄送目的地址

// InternetAddress[] toscc = InternetAddress.parse(ccAddr);

// msg.setRecipients(Message.RecipientType.CC, toscc);

//

//密送目的地址

// InternetAddress[] tosbcc = InternetAddress.parse(bccAddr);

// msg.setRecipients(Message.RecipientType.BCC, tosbcc);

//发送邮件

boolean bool = sendMail.sendMail(msg);

if(bool){

System.out.println("发送成功");

}else{

System.out.println("发送失败");

}

}

}

}

public Session getSession(String smtpServer, String userName, String password){

// 192.168.1.245

// user2

// yyaccp

Session session = null;

try{

Properties props = new Properties();

props.put("mail.smtp.host", smtpServer); //例如:202.108.44.206 smtp.163.com

props.put("mail.smtp.auth", "true"); //认证是否设置

UserAuthentication authen = new UserAuthentication();

authen.setPassword(password);

authen.setUserName(userName);

session = Session.getDefaultInstance(props, authen);

}catch(Exception e){

e.printStackTrace();

}

return session;

}

public Message getMessage(Session session, String subject, String text){

Message msg = null;

try{

msg = new MimeMessage(session);

msg.setText(text);

msg.setSubject(subject);

}catch(Exception e){

e.printStackTrace();

}

return msg;

}

public boolean sendMail(Message msg){

boolean bool = false;

try {

Transport.send(msg);

bool = true;

} catch (MessagingException ex) {

ex.printStackTrace();

}

return bool;

}

public Message getMessage(Session session, String subject, String text, String[] archives){

// d:/temp/saa.txt

Message msg = null;

try{

Multipart contentPart = new MimeMultipart();

// 生成Message对象

msg = new MimeMessage(session);

// 设置邮件内容

msg.setContent(contentPart);

// 设置邮件标题

msg.setSubject(subject);

// 组织邮件内容,包括邮件的文本内容和附件

// 1 邮件文本内容

MimeBodyPart textPart = new MimeBodyPart();

textPart.setText(text);

// 将文本部分,添加到邮件内容

contentPart.addBodyPart(textPart);

// 2 附件

if(archives != null){

for(int i=0; i<archives.length; i++){

MimeBodyPart archivePart = new MimeBodyPart();

//选择出每一个附件文件名

String filename = archives[i];

//得到数据源

FileDataSource fds = new FileDataSource(filename);

//得到附件本身并至入BodyPart

archivePart.setDataHandler(new DataHandler(fds));

//得到文件名同样至入BodyPart

archivePart.setFileName(fds.getName());

// 将附件添加到附件集

contentPart.addBodyPart(archivePart);

}



-

-

bsp; }

}catch(Exception e){

e.printStackTrace();

}

return msg;

}

/**

* 获取文本文件内容

* @param path String

* @throws IOException

* @return String

*/

public String getFile(String path) throws IOException {

//读取文件内容

char[] chrBuffer = new char[10];//缓冲十个字符

int intLength;

String s = "";//文件内容字符串

FileReader fis = new FileReader(path);

while ( (intLength = fis.read(chrBuffer)) != -1) {

String temp = String.valueOf(chrBuffer);//转换字符串

s = s + temp;//累加字符串

}

return s;

}

}



ReceiveMailTest.java

package cn.com.javaweb.mail;

import javax.mail.Message;

import javax.mail.Folder;

import javax.mail.Store;

import javax.mail.FetchProfile;

import javax.mail.BodyPart;

import javax.mail.Multipart;

import javax.mail.Part;

import java.io.InputStream;

import java.io.FileOutputStream;

import java.io.File;

import java.util.Properties;

import javax.mail.Session;

public class ReceiveMailTest {

private Folder inbox;

private Store store;

//连接邮件服务器,获得所有邮件的列表

public Message[] getMail(String host, String name, String password) throws

Exception {

Properties prop = new Properties();

prop.put("mail.pop3.host", host);

Session session = Session.getDefaultInstance(prop);

store = session.getStore("pop3");

store.connect(host, name, password);

inbox = store.getDefaultFolder().getFolder("INBOX");

inbox.open(Folder.READ_ONLY);

Message[] msg = inbox.getMessages();

FetchProfile profile = new FetchProfile();

profile.add(FetchProfile.Item.ENVELOPE);

profile.add(FetchProfile.Item.FLAGS);

profile.add("X-Mailer");

inbox.fetch(msg, profile);

return msg;

}

//处理任何一种邮件都需要的方法

private void handle(Message msg) throws Exception {

System.out.println("邮件主题:" + msg.getSubject());

System.out.println("邮件作者:" + msg.getFrom()[0].toString());

System.out.println("发送日期:" + msg.getSentDate());

}

//处理文本邮件

public void handleText(Message msg) throws Exception {

this.handle(msg);

System.out.println("邮件内容:" + msg.getContent());

}

//处理Multipart邮件,包括了保存附件的功能

public void handleMultipart(Message msg) throws Exception {

String disposition;

BodyPart part;

// 1、从Message中取到Multipart

// 2、遍历Multipart里面得所有bodypart

// 3、判断BodyPart是否是附件,

// 如果是,就保存附件

// 否则就取里面得文本内容

Multipart mp = (Multipart) msg.getContent();

int mpCount = mp.getCount(); //Miltipart的数量,用于除了多个part,比如多个附件

for (int m = 0; m < mpCount; m++) {

this.handle(msg);

part = mp.getBodyPart(m);

disposition = part.getDisposition();

if (disposition != null && disposition.equals(Part.ATTACHMENT)) { //判断是否有附件

this.saveAttach(part);//这个方法负责保存附件,注释掉是因为附件可能有病毒,请清理信箱之后再取掉注释

} else {

System.out.println(part.getContent());

}

}

}

private void saveAttach(BodyPart part)



-

-

throws Exception {

String temp = part.getFileName(); //得到未经处理的附件名字

System.out.println("*********temp=" + temp);

System.out.println("**********" + base64Decoder(temp));

String s = temp;//temp.substring(11, temp.indexOf("?=") - 1); //去到header和footer

//文件名一般都经过了base64编码,下面是解码

String fileName = s;//this.base64Decoder(s);

System.out.println("有附件:" + fileName);

InputStream in = part.getInputStream();

FileOutputStream writer = new FileOutputStream(new File("d:/temp/"+fileName));

byte[] content = new byte[255];

int read = 0;

while ((read = in.read(content)) != -1) {

writer.write(content);

}

writer.close();

in.close();

}

//base64解码

private String base64Decoder(String s) throws Exception {

sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

byte[] b = decoder.decodeBuffer(s);

//sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();

//String str = encoder.encode(bytes);

return (new String(b));

}

//关闭连接

public void close() throws Exception {

if (inbox != null) {

inbox.close(false);

}

if (store != null) {

store.close();

}

}

public static void main(String args[]) {

String host = "192.168.1.245";

String name = "user2";

String password = "yyaccp";

ReceiveMailTest receiver = new ReceiveMailTest();

try {

Message[] msg = receiver.getMail(host, name, password);

for (int i = 0; i < msg.length; i++) {

if (msg[i].isMimeType("text/*")) { //判断邮件类型

receiver.handleText(msg[i]);

} else {

receiver.handleMultipart(msg[i]);

}

System.out.println("****************************");

}

receiver.close();

} catch (Exception e) {

e.printStackTrace();

System.out.println(e);

}

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: