-----------话不多说,实现了接收邮件,发送邮件,解析内容有图片和附件
–邮件类 emailService
/**
* 判断时间是不是今天
* @param date
* @return 是返回true,不是返回false
*/
private static boolean isNow(Date date) {
//当前时间
Date now = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
//获取今天的日期
String nowDay = sf.format(now);
//对比的时间
String day = sf.format(date);
return day.equals(nowDay);
}
/**
* 接收邮件
* test1()
*/
public void test1() throws Exception{
Properties props = System.getProperties();
props.put("mail.smtp.host", "**填写host**");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
URLName urln = new URLName("pop3", "mail.sonic-teleservices.com", 110, null,
"**填写邮箱名称**", "**填写邮箱密码**");
Store store = session.getStore(urln);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();
// 获取全部邮件-数量
System.out.println("Messages's length: " + message.length);
try {
// 获取数据库现有邮件
List<String> uidLists = email_botDao.getUidLists();
if (folder instanceof POP3Folder) {
POP3Folder inbox = (POP3Folder) folder;
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
MimeMessage mimeMessage = (MimeMessage) messages[i];
// 邮件太多了,isNow 判断是今天的才进行
if(isNow(mimeMessage.getSentDate())){
String uid = inbox.getUID(mimeMessage);
// 此处和数据库匹配,不存在才进行
if(uidLists.contains(uid)){
//System.out.println("POP3Folder uid=" + uid+"存在");
}else{
//System.out.println("POP3Folder uid=" + uid+"不存在");
test2(mimeMessage,session,uid,i);
}
}
}
} else if (folder instanceof IMAPFolder) {
IMAPFolder inbox = (IMAPFolder) folder;
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
MimeMessage mimeMessage = (MimeMessage) messages[i];
String uid = Long.toString(inbox.getUID(mimeMessage));
if(uidLists.contains(uid)){
//System.out.println("IMAPFolder uid=" + uid+",存在");
}else{
//System.out.println("IMAPFolder uid=" + uid+",不存在");
test2(mimeMessage,session,uid,i);
}
}
} else {
logger.error("no have this folder {}", folder);
}
}catch (Exception e){
logger.error(e.toString(), folder);
}
//释放资源
if (folder != null) folder.close(true);
if (store != null) store.close();
}
/**
* 接收邮件-不存在数据库,分析邮件
* test2()
*/
public void test2(MimeMessage mimeMessage,Session session,String uid,int i) throws Exception{
ReciveMail pmm = new ReciveMail(mimeMessage);;
System.out.println("==============================第" + (i + 1) + "封===========================");
Map<String, String> imgs = new HashMap<String, String>();
// 获得邮件内容===============
pmm.setAttachPath("c:\\ddd"); //附件位置
pmm.getMailContent(mimeMessage,imgs);
pmm.saveAttachMent(mimeMessage);
String tmpContent = pmm.getBodyHtml();
// 内容存在图片,上传到服务器后更换文本;注意下方链接是自己公网访问。
// 替换原文中的图片,原始图片标签为<img src="cid:image001.jpg@01D24963.3B4B8280">
for (String contentId : imgs.keySet()) {
String replacedText = "cid:" + contentId.replace("<", "").replace(">", "");
tmpContent = tmpContent.replace(replacedText, "https://xxxxx/resourceEmailbot/"+imgs.get(contentId));
}
pmm.setBodyHtml(tmpContent);
//邮件内容中的图片处理
System.out.println("Message " + i + " Message-ID: " + pmm.getMessageId());
System.out.println("form: " + pmm.getFrom());
System.out.println("to: " + pmm.getMailAddress("to"));
System.out.println("cc: " + pmm.getMailAddress("cc"));
System.out.println("bcc: " + pmm.getMailAddress("bcc"));
System.out.println("subject: " + pmm.getSubject());
System.out.println("sentdate: " + pmm.getSentDate());
System.out.println("replysign: " + pmm.getReplySign());
System.out.println("hasRead: " + pmm.isNew());
System.out.println("containAttachment: " + pmm.isContainAttach(mimeMessage));
System.out.println("Text: \r\n" + pmm.getBodyText());
System.out.println("Html:\r\n"+pmm.getBodyHtml());
// 发邮件
pmm.replyMail(session,pmm,module);
}
–解析邮件类
/**
* 解析邮件
* ReciveMail() -class
*/
public class ReciveMail {
private MimeMessage mimeMessage = null;
private String saveAttachPath = ""; // 附件下载后的存放目录
private StringBuffer bodytext = new StringBuffer();// 存放邮件内容
private StringBuffer bodyhtml = new StringBuffer();// 存放邮件内容-html
private String dateformat = "yyyy-MM-dd HH:mm:ss"; // 默认的日前显示格式
private String path = ""; // 路径lists
public ReciveMail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
/**
* 设置为已读--测试无效,我也没用到
*/
public void setFlag() throws Exception {
this.mimeMessage.setFlag(Flags.Flag.SEEN, true);
}
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();
personal = MimeUtility.decodeText(personal);
if (personal == null)
personal = "";
String fromaddr = personal + "<" + from + ">";
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 + "<" + email + ">";
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 Date getSentDate() throws Exception {
Date sentdate = mimeMessage.getSentDate();
//SimpleDateFormat format = new SimpleDateFormat(dateformat);
//return format.format(sentdate);
return sentdate;
}
/**
* 获得邮件发送日期
*/
public String getSentDate1() throws Exception {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}
/**
* 获得邮件正文内容
*/
public String getBodyText() {
return bodytext.toString();
}
/**
* 获得邮件正文内容-html
*/
public String getBodyHtml() {
return bodyhtml.toString();
}
public void setBodyHtml(String s) {
bodyhtml = new StringBuffer(s);
}
/**
* 获得path
*/
public String getPath() {
return path;
}
/**
* 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
*/
public void getMailContent(Part part, Map<String, String> imgs) 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());
bodyhtml.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),imgs);
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent(),imgs);
} else if (part.isMimeType("image/*")) {// 检查内容是否为内嵌图片
Object content = part.getContent();
String contentID = ((String[]) part.getHeader("Content-ID"))[0];
InputStream in = (InputStream) content;
byte[] bArray = new byte[in.available()];
while (((InputStream) in).available() > 0) {
int result = (int) (((InputStream) in).read(bArray));
if (result == -1) {
break;
}
}
in.close();
// 文件下载开始
String fileName = new Date( ).getTime() + ".jpg";
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:\\ddd";
} else {
separator = "/";
// linux 环境上传位置。我使用nginx,后面做个访问就行了
storedir = "/usr/local/nginx/resource/resourceEmailbot";
}
File storefile = new File(storedir + separator + fileName);
storefile.setWritable(true, false);
FileOutputStream f2 = new FileOutputStream(storefile);
f2.write(bArray);
f2.close();
in.close();
imgs.put(contentID, fileName);
// 文件下载结束
}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;
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);
}
if (fileName.toLowerCase().indexOf("gbk") != -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:\\ddd";
} else {
separator = "/";
// linux 环境上传位置。我使用nginx,后面做个访问就行了
storedir = "/usr/local/nginx/resource/resourceEmailbot";
}
File storefile = new File(storedir + separator + fileName);
storefile.setWritable(true, false);
System.out.println("storefile's path: " + storefile.toString());
//path += ";"+storefile.toString();
path += ";"+fileName;
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();
}
}
/**
* 转发邮件
* @param session
* @param mail
* @throws Exception
* @throws MessagingException
*/
public void forwardMail(Session session, ReciveMail mail) throws Exception, MessagingException{
session.setDebug(true);
MimeMessage fordward = new MimeMessage(session);
//fordward.setFrom(mail.getFrom());
fordward.setFrom(new InternetAddress("**填写发送邮件**"));
fordward.setSubject(mail.getSubject());
//fordward.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiveAddress));
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mail.getMailContent((Part)mail.mimeMessage,null);
mbp.setContent("<meta http-equiv=Content-Type content=text/html; charset=GBK>"+
mail.getBodyText(), "text/html;charset=gb2312");
mp.addBodyPart(mbp);
fordward.setContent(mp); //Multipart加入到信件
fordward.setSentDate(new Date()); //设置信件头的发送日期
//发送信件
fordward.saveChanges();
Transport.send(fordward);
}
// 回复邮件的内容 尾部
public static String tail_bot = " 谢谢";
/**
* 回复邮件
* @param session
* @param mail
* @throws Exception
*/
public boolean replyMail(Session session, ReciveMail mail, RestResultModule module){
try {
MimeMessage msg = (MimeMessage) mail.mimeMessage.reply(false);
msg.setFrom(new InternetAddress("**填写发送人邮件**"));
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
// 编辑内容
String s = "<meta http-equiv=Content-Type content=text/html; charset=GBK>" +
"<br>HI 客户,<br><br>" +
"<div style=\"margin-left: 10px;\">" +
"**填写自己回复的内容**" +
" </div>" +
"<br><br>" +tail_bot+
"<br><br>---- 在 "+mail.getSentDate1()+"<"+mail.getMailAddress("to")+"> 上回复 ----<br><br><br><br>" +
"<blockquote>" +
""+mail.getBodyHtml()+
"</blockquote>" +
"";
mbp.setContent(s, "text/html;charset=gb2312");
mp.addBodyPart(mbp);
msg.setContent(mp);
msg.setSentDate(new Date());
msg.saveChanges();
Transport trans = session.getTransport("smtp");
trans.connect("**填写邮件host**", "**填写发送人邮件的名称**", "**填写发送人邮件的密码**");
trans.sendMessage(msg, msg.getAllRecipients());
trans.close();
return true;
}catch (Exception e){
System.out.println("回复邮件错误:"+e);
return false;
}
}
}
–项目启动,执行线程-接收邮件
/**
* 项目启动后,执行下面方法
*/
@Component
public class BotRunner implements CommandLineRunner {
@Resource
private BotService botService;
@Override
public void run(String... var1) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("------------启动线程------------" + format.format(new Date()));
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override public synchronized void run() {
try {
botService.test1();
}
}catch (Exception e){
System.out.println("线程错误");
}
}
}, 0, 3000);
}
}
复制过去即可用。还有几个疑问
- 上传到linux 使用nginx做转发,可参考我这个文章
linux nginx 访问资源路径,位置
2.上传图片获取附件时访问不到,可能是linux权限问题,可参考我这个文章
Javaweb上传Linux 没有读写权限