展开全部

package com.gwxc.hz.mail.demo;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Properties;

import javax.mail.BodyPart;

import javax.mail.Flags;

import javax.mail.Folder;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.NoSuchProviderException;

import javax.mail.Part;

import javax.mail.Session;

import javax.mail.Store;

import javax.mail.URLName;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeUtility;

public class ReciveOneMail {

/**

* 有一封邮件就需要建立一个ReciveMail对象

*/

private MimeMessage mimeMessage = null;

private String saveAttachPath = ""; // 附件下载后的存放目录

private StringBuffer bodytext = new StringBuffer();// 存放邮件内容

private String dateformat = "yy-MM-dd HH:mm"; // 默认的日32313133353236313431303231363533e78988e69d8331333236383532前显示格式

public ReciveOneMail(MimeMessage mimeMessage) {

this.mimeMessage = mimeMessage;

}

public void setMimeMessage(MimeMessage mimeMessage) {

this.mimeMessage = mimeMessage;

}

/**

* 获得发件人的地址和姓名

*/

public String getFrom() throws Exception {

InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();

String from = address[0].getAddress();

if (from == null)

from = "";

String personal = address[0].getPersonal();

if (personal == null)

personal = "";

String fromaddr = personal + "";

return fromaddr;

}

/**

* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址

*/

public String getMailAddress(String type) throws Exception {

String mailaddr = "";

String addtype = type.toUpperCase();

InternetAddress[] address = null;

if (addtype.equals("TO") || addtype.equals("CC")

|| addtype.equals("BCC")) {

if (addtype.equals("TO")) {

address = (InternetAddress[]) mimeMessage

.getRecipients(Message.RecipientType.TO);

} else if (addtype.equals("CC")) {

address = (InternetAddress[]) mimeMessage

.getRecipients(Message.RecipientType.CC);

} else {

address = (InternetAddress[]) mimeMessage

.getRecipients(Message.RecipientType.BCC);

}

if (address != null) {

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

String email = address[i].getAddress();

if (email == null)

email = "";

else {

email = MimeUtility.decodeText(email);

}

String personal = address[i].getPersonal();

if (personal == null)

personal = "";

else {

personal = MimeUtility.decodeText(personal);

}

String compositeto = personal + "";

mailaddr += "," + compositeto;

}

mailaddr = mailaddr.substring(1);

}

} else {

throw new Exception("Error emailaddr type!");

}

return mailaddr;

}

/**

* 获得邮件主题

*/

public String getSubject() throws MessagingException {

String subject = "";

try {

subject = MimeUtility.decodeText(mimeMessage.getSubject());

if (subject == null)

subject = "";

} catch (Exception exce) {

}

return subject;

}

/**

* 获得邮件发送日期

*/

public String getSentDate() throws Exception {

Date sentdate = mimeMessage.getSentDate();

SimpleDateFormat format = new SimpleDateFormat(dateformat);

return format.format(sentdate);

}

/**

* 获得邮件正文内容

*/

public String getBodyText() {

return bodytext.toString();

}

/**

* 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析

*/

public void getMailContent(Part part) throws Exception {

String contenttype = part.getContentType();

int nameindex = contenttype.indexOf("name");

boolean conname = false;

if (nameindex != -1)

conname = true;

System.out.println("CONTENTTYPE: " + contenttype);

if (part.isMimeType("text/plain") && !conname) {

bodytext.append((String) part.getContent());

} else if (part.isMimeType("text/html") && !conname) {

bodytext.append((String) part.getContent());

} else if (part.isMimeType("multipart/*")) {

Multipart multipart = (Multipart) part.getContent();

int counts = multipart.getCount();

for (int i = 0; i < counts; i++) {

getMailContent(multipart.getBodyPart(i));

}

} else if (part.isMimeType("message/rfc822")) {

getMailContent((Part) part.getContent());

} else {

}

}

/**

* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"

*/

public boolean getReplySign() throws MessagingException {

boolean replysign = false;

String needreply[] = mimeMessage

.getHeader("Disposition-Notification-To");

if (needreply != null) {

replysign = true;

}

return replysign;

}

/**

* 获得此邮件的Message-ID

*/

public String getMessageId() throws MessagingException {

return mimeMessage.getMessageID();

}

/**

* 【判断此邮件是否已读,如果未读返回返回false,反之返回true】

*/

public boolean isNew() throws MessagingException {

boolean isnew = false;

Flags flags = ((Message) mimeMessage).getFlags();

Flags.Flag[] flag = flags.getSystemFlags();

System.out.println("flags's length: " + flag.length);

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

if (flag[i] == Flags.Flag.SEEN) {

isnew = true;

System.out.println("seen Message.......");

break;

}

}

return isnew;

}

/**

* 判断此邮件是否包含附件

*/

public boolean isContainAttach(Part part) throws Exception {

boolean attachflag = false;

String contentType = part.getContentType();

if (part.isMimeType("multipart/*")) {

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

for (int i = 0; i < mp.getCount(); i++) {

BodyPart mpart = mp.getBodyPart(i);

String disposition = mpart.getDisposition();

if ((disposition != null)

&& ((disposition.equals(Part.ATTACHMENT)) || (disposition

.equals(Part.INLINE))))

attachflag = true;

else if (mpart.isMimeType("multipart/*")) {

attachflag = isContainAttach((Part) mpart);

} else {

String contype = mpart.getContentType();

if (contype.toLowerCase().indexOf("application") != -1)

attachflag = true;

if (contype.toLowerCase().indexOf("name") != -1)

attachflag = true;

}

}

} else if (part.isMimeType("message/rfc822")) {

attachflag = isContainAttach((Part) part.getContent());

}

return attachflag;

}

/**

* 【保存附件】

*/

public void saveAttachMent(Part part) throws Exception {

String fileName = "";

if (part.isMimeType("multipart/*")) {

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

for (int i = 0; i < mp.getCount(); i++) {

BodyPart mpart = mp.getBodyPart(i);

String disposition = mpart.getDisposition();

if ((disposition != null)

&& ((disposition.equals(Part.ATTACHMENT)) || (disposition

.equals(Part.INLINE)))) {

fileName = mpart.getFileName();

if (fileName.toLowerCase().indexOf("gb2312") != -1) {

fileName = MimeUtility.decodeText(fileName);

}

saveFile(fileName, mpart.getInputStream());

} else if (mpart.isMimeType("multipart/*")) {

saveAttachMent(mpart);

} else {

fileName = mpart.getFileName();

if ((fileName != null)

&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {

fileName = MimeUtility.decodeText(fileName);

saveFile(fileName, mpart.getInputStream());

}

}

}

} else if (part.isMimeType("message/rfc822")) {

saveAttachMent((Part) part.getContent());

}

}

/**

* 【设置附件存放路径】

*/

public void setAttachPath(String attachpath) {

this.saveAttachPath = attachpath;

}

/**

* 【设置日期显示格式】

*/

public void setDateFormat(String format) throws Exception {

this.dateformat = format;

}

/**

* 【获得附件存放路径】

*/

public String getAttachPath() {

return saveAttachPath;

}

/**

* 【真正的保存附件到指定目录里】

*/

private void saveFile(String fileName, InputStream in) throws Exception {

String osName = System.getProperty("os.name");

String storedir = getAttachPath();

String separator = "";

if (osName == null)

osName = "";

if (osName.toLowerCase().indexOf("win") != -1) {

separator = "\\";

if (storedir == null || storedir.equals(""))

storedir = "c:\\tmp";

} else {

separator = "/";

storedir = "/tmp";

}

File storefile = new File(storedir + separator + fileName);

System.out.println("storefile's path: " + storefile.toString());

// for(int i=0;storefile.exists();i++){

// storefile = new File(storedir+separator+fileName+i);

// }

BufferedOutputStream bos = null;

BufferedInputStream bis = null;

try {

bos = new BufferedOutputStream(new FileOutputStream(storefile));

bis = new BufferedInputStream(in);

int c;

while ((c = bis.read()) != -1) {

bos.write(c);

bos.flush();

}

} catch (Exception exception) {

exception.printStackTrace();

throw new Exception("文件保存失败!");

} finally {

bos.close();

bis.close();

}

}

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

Properties props = System.getProperties();

props.put("mail.smtp.host", "smtp.163.com");

props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);

URLName urln = new URLName("pop3", "pop3.163.com", 110, null,

"dt_cj2004", "abcdefghij");

Store store = session.getStore(urln);

store.connect();

Folder folder = store.getFolder("spool");

//Folder folder = store.getFullName();

folder.open(Folder.READ_ONLY);

//System.out.println(folder.getNewMessageCount());

Message message[] = folder.getMessages();

System.out.println("Messages's length: " + message.length);

ReciveOneMail pmm = null;

/*

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

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

pmm = new ReciveOneMail((MimeMessage) message[i]);

System.out

.println("Message " + i + " subject: " + pmm.getSubject());

System.out.println("Message " + i + " sentdate: "

+ pmm.getSentDate());

System.out.println("Message " + i + " replysign: "

+ pmm.getReplySign());

System.out.println("Message " + i + " hasRead: " + pmm.isNew());

System.out.println("Message " + i + " containAttachment: "

+ pmm.isContainAttach((Part) message[i]));

System.out.println("Message " + i + " form: " + pmm.getFrom());

System.out.println("Message " + i + " to: "

+ pmm.getMailAddress("to"));

System.out.println("Message " + i + " cc: "

+ pmm.getMailAddress("cc"));

System.out.println("Message " + i + " bcc: "

+ pmm.getMailAddress("bcc"));

pmm.setDateFormat("yy年MM月dd日 HH:mm");

System.out.println("Message " + i + " sentdate: "

+ pmm.getSentDate());

System.out.println("Message " + i + " Message-ID: "

+ pmm.getMessageId());

// 获得邮件内容===============

pmm.getMailContent((Part) message[i]);

System.out.println("Message " + i + " bodycontent: \r\n"

+ pmm.getBodyText());

pmm.setAttachPath("c:\\");

pmm.saveAttachMent((Part) message[i]);

}

*/

}

}

package com.gwxc.hz.mail.demo;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class MyMailTest {

/**

* @param args

*/

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

// 会话===========================

Properties props = System.getProperties();

props.put("mail.smtp.host", "smtp.163.com");

props.put("mail.smtp.auth", "true");// 需要验证

Session session = Session.getDefaultInstance(props, null);

// msg 设置=======================

MimeMessage mimeMsg = new MimeMessage(session);

// 设置标题

mimeMsg.setSubject("标题test");

// 设置内容----begin

Multipart mp = new MimeMultipart();

// 添加文本

BodyPart bp1 = new MimeBodyPart();

bp1.setContent("文本内容", "text/html;charset=GB2312");

mp.addBodyPart(bp1);

// 添加附件

BodyPart bp2 = new MimeBodyPart();

FileDataSource fileds = new FileDataSource("c:\\boot.ini");

bp2.setDataHandler(new DataHandler(fileds));

bp2.setFileName(fileds.getName());

mp.addBodyPart(bp2);

mimeMsg.setContent(mp);

// 设置内容----end

mimeMsg.setFrom(new InternetAddress("xiangzhengyan@163.com"));

mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress

.parse("xiangyh@asiacom-online.com"));

mimeMsg.saveChanges();

// 传输==================================

Transport transport = session.getTransport("smtp");

transport.connect((String) props.get("mail.smtp.host"),

"xiangzhengyan", "pass");

transport.sendMessage(mimeMsg, mimeMsg

.getRecipients(Message.RecipientType.TO));

transport.close();

}

}

本回答被提问者采纳

已赞过

已踩过<

你对这个回答的评价是?

评论

收起

java mail urlname_javamail收发信件时,服务器,收发方的名称应该怎样设置才有效呢相关推荐

  1. java Mail imap协议获取到得邮件文件夹名称

    java Mail imap协议获取到得邮件文件夹名称 Imap协议 QQ imap.qq.com 端口:143 获取得邮件 Folder[] list 中 1.其他文件夹 2.INBOX 3.Sen ...

  2. java mail 收 附件_使用 JavaMail 收发邮件,解决中文附件问题

    几天来一直在开发一个项目,其中一部分需要用 JavaMail 收发邮件,于是就在网上找了一些相关的源代码,最后经过整理和修改,终于好使了,希望能够给使用 JavaMail 收发邮件的朋友提供一个参考 ...

  3. 飒,NTP校时服务器在银行大楼系统方案

    飒,NTP校时服务器在银行大楼系统方案 飒,NTP校时服务器在银行大楼系统方案 飒,NTP校时服务器在银行弱电系统方案 时间同步才是各个系统协同工作的基础. 方案背景: 银行大楼作为银行业务管理的主体 ...

  4. java mail 收发邮件

    java mail 收发邮件 1.发件 2.收件 1.发件 package base.util; /* Some SMTP servers require a username and passwor ...

  5. 有人串口转wifi模块 httpd client通信示例-用户使用网页通过服务器收发串口数据源码 小黄人软件

    有人串口转wifi模块 httpd client通信示例-用户使用网页通过服务器收发串口数据 功能:用户使用网页通过服务器收发串口数据,转发信息通过文件转存.网页自动更新串口发来的数据,网页发送数据到 ...

  6. 使用 Java Mail 实现注册时邮箱激活验证功能

    最近在做毕设中实现注册功能时使用到了邮箱激活验证,在此总结下. 简介 JavaMail 是提供给开发者处理电子邮件相关的编程接口,它是 SUN 发布的用来处理 email 的 API ,它可以方便地执 ...

  7. ESP8266与MQTT服务器收发送数据

    陈拓 2021/04/20-2021/04/25 1. 概述 我们在<Win10-Ubuntu子系统构建ESP8266_RTOS_SDK开发环境> https://zhuanlan.zhi ...

  8. php socket发数据打印,PHP向socket服务器收发数据的方法

    这篇文章主要介绍了PHP向socket服务器收发数据的方法,分析了socket收发数据的方法,并介绍了socket常用函数,需要的朋友可以参考下 本文实例讲述了PHP向socket服务器收发数据的方法 ...

  9. Python实战技巧(11)使用python收发邮件时需要的邮箱授权码如何获取

    Python实战技巧(1)Python字典类型数据如何递归地通过点'.'的方式访问 Python实战技巧(2)Python的pdb调试代码方法详解 Python实战技巧(3)多版本兼容安装部署(py2 ...

最新文章

  1. 《评人工智能如何走向新阶段》后记(再续3)
  2. Red Hat Linux、rhel 和 Fedora Core 以及 Centos 区别与联系
  3. 3. Android框架和工具之 xUtils(BitmapUtils)
  4. 02_Android写xml文件和读xml文件
  5. python processpoolexector 释放内存_使用Python的multiprocessing.pool,内存使用量不断增长...
  6. 使用计算机时什么是开机键什么是关机键,计算器上的开机键是关机键是
  7. java导出excel_Hutool Java 工具类库导出 Excel,超级简单!
  8. tensorflow-gpu_tensorflow GPU环境安装踩坑日记
  9. Python---字符串与列表
  10. mysql java safe model_被 MySQL sql_mode 深深伤害( 中 )
  11. mysql中如何将一个表中的部分记录合并,mysql - 如何从一个表中获取所有产品并从另一个包含多行的表中合并一行? - SO中文参考 - www.soinside.com...
  12. 网络安全设备Bypass功能
  13. Python实现Reed-Xiaoli(RX)高光谱目标检测算法
  14. that being said
  15. 动态DNS的定义以及优缺点有哪些
  16. 怪盗基德的滑翔翼 线性DP 最长上升子序列
  17. 华师新生研讨课 课后心得004
  18. matlab:数组定义
  19. 关于网络安全法的个人理解
  20. EXP-00002错误解决方法

热门文章

  1. 目标检测特殊层:PSROIPooling详解
  2. Linux中断处理流程
  3. fprintf,sprintf,sscanf,fscanf
  4. asp.net mvc的初学
  5. 行为型模式:中介者模式
  6. (转)Eclipse New Server 【无法输入server name】
  7. map and flatmap 区别
  8. MPAndroidChart——饼图
  9. Jquery 日期差函数 修改 对火狐进行兼容
  10. OpenGL png图片 纹理贴图,去除png图片黑边