博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mail spy
阅读量:6840 次
发布时间:2019-06-26

本文共 8658 字,大约阅读时间需要 28 分钟。

  hot3.png

MailSpy.java

package forest;import java.io.IOException;import java.security.Security;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Properties;import java.util.ResourceBundle;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.LogRecord;import java.util.logging.Logger;import javax.activation.DataHandler;import javax.mail.Authenticator;import javax.mail.Flags;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Part;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Store;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import com.sun.net.ssl.internal.ssl.Provider;public class MailSpy {	public static Logger log = Logger.getLogger("MailSpy");	private static ResourceBundle mailProperties = ResourceBundle.getBundle("forest.mail");	private static String username;	private static String password;	private static Properties props = new Properties();	private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	static {		try {			FileHandler fh = new FileHandler(mailProperties.getString("logFile"));			fh.setFormatter(new Formatter() {				@Override				public String format(LogRecord record) {					return String.format("%s [%s] - %s\n", sf.format(record.getMillis()), record.getLevel(), record							.getMessage());				}			});			log.addHandler(fh);		} catch (SecurityException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		}		Security.addProvider(new Provider());		System.setProperty("javax.net.ssl.trustStore", mailProperties.getString("jssecacerts"));		for (String key : mailProperties.keySet()) {			props.setProperty(key, mailProperties.getString(key));		}		username = mailProperties.getString("username");		password = mailProperties.getString("password");	}	public static void main(String[] args) {		while (true) {			try {				MailSpy util = new MailSpy();				MailMessage mailMessage = util.getMail();				if (mailMessage != null) {					log.info("foward mail");					util.forwardMail(mailMessage);				}			} catch (Exception e) {				log.severe(e.getMessage());			}			try {				Thread.sleep(10000);			} catch (InterruptedException e) {				e.printStackTrace();			}		}	}	/**	 *  pharmgeneral@dh.gov.hk pass0424 	 */	public void forwardMail(MailMessage mailMessage) throws AddressException, MessagingException {		Session session = Session.getDefaultInstance(props, new MyAuthenticator(username, password));		session.setDebug(false);		MimeMessage msg = new MimeMessage(session);		if (!mailMessage.getBodyPart().isEmpty()) {			MimeMultipart multipart = new MimeMultipart();			for (MimeBodyPart body : mailMessage.getBodyPart()) {				multipart.addBodyPart(body);			}			msg.setContent(multipart);		} else {			msg.setText(mailMessage.getBodyText());		}		//msg.setFrom(new InternetAddress(mailMessage.getFrom()));		msg.setFrom(new InternetAddress(username));		msg.setSender(new InternetAddress(mailMessage.getFrom()));		msg.setRecipients(Message.RecipientType.TO, mailProperties.getString("forwardTo"));		//msg.setRecipients(Message.RecipientType.TO, "PRS2.AP1@hp.com");		log.config("Sender " + mailMessage.getFrom() + ", Cc " + mailProperties.getString("forwardTo"));		msg.setSubject(mailMessage.getSubject());		msg.setSentDate(mailMessage.getSent());		Transport.send(msg);		log.info("subject: " + mailMessage.getSubject() + " is sent.");	}	public MailMessage getMail() {		Session session = Session.getDefaultInstance(props, new MyAuthenticator(username, password));		Store store = null;		MailMessage mailMessage = null;		try {			session.setDebug(false);			store = session.getStore();			store.connect();			Folder folder = store.getFolder("INBOX");			folder.open(Folder.READ_WRITE);			int count = folder.getMessageCount();			if (count == 0) {				log.info("no message");			} else {				mailMessage = new MailMessage();				Message message = folder.getMessage(1);				Object content = message.getContent();				mailMessage.setFrom(InternetAddress.toString(message.getFrom()));				//mailMessage.setReplyTo(InternetAddress.toString(message.getReplyTo()));				//mailMessage.setTo(InternetAddress.toString(message.getRecipients(Message.RecipientType.TO)));				//mailMessage.setCc(InternetAddress.toString(message.getRecipients(Message.RecipientType.CC)));				mailMessage.setSubject(message.getSubject());				mailMessage.setSent(message.getSentDate());				if (content instanceof MimeMultipart) {					MimeMultipart mp = (MimeMultipart) content;					for (int i = 0, n = mp.getCount(); i < n; i++) {						Part part = mp.getBodyPart(i);						DataHandler hd = part.getDataHandler();						MimeBodyPart messageBodyPart = new MimeBodyPart();						messageBodyPart.setDataHandler(new DataHandler(hd.getDataSource()));						mailMessage.getBodyPart().add(messageBodyPart);						/*String disposition = part.getDisposition();						if (disposition == null) {							DataHandler hd = part.getDataHandler();							MimeBodyPart messageBodyPart = new MimeBodyPart();							messageBodyPart.setDataHandler(new DataHandler(hd.getDataSource()));							//messageBodyPart.setFileName(fileName);							mailMessage.getBodyPart().add(messageBodyPart);						}						if ((disposition != null)								&& (disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE)))) {							String fileName = part.getFileName();							log.info("file name: " + fileName);							InputStream in = part.getInputStream();							ByteArrayDataSource dataSource = new ByteArrayDataSource(in, part.getContentType());							MimeBodyPart messageBodyPart = new MimeBodyPart();							messageBodyPart.setDataHandler(new DataHandler(dataSource));							messageBodyPart.setFileName(fileName);							mailMessage.getBodyPart().add(messageBodyPart);						}*/					}				} else {					log.info("content of text/plain " + content);					mailMessage.setBodyText(content.toString());				}				message.setFlag(Flags.Flag.DELETED, true);			}			folder.close(true);		} catch (Exception e) {			e.printStackTrace();		} finally {			try {				log.fine("store closed");				store.close();			} catch (MessagingException e) {				// TODO Auto-generated catch block				e.printStackTrace();			}		}		return mailMessage;	}}class MyAuthenticator extends Authenticator {	private String username;	private String password;	public MyAuthenticator(String username, String password) {		this.username = username;		this.password = password;	}	protected PasswordAuthentication getPasswordAuthentication() {		MailSpy.log.config("username " + username + " , password " + password);		return new PasswordAuthentication(username, password);	}}class MailMessage {	private String from;	private String replyTo;	private String to;	private String cc;	private Date sent;	private String subject;	private String bodyText;	private List
bodyPart = new ArrayList
(); public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getReplyTo() { return replyTo; } public void setReplyTo(String replyTo) { this.replyTo = replyTo; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Date getSent() { return sent; } public void setSent(Date sent) { this.sent = sent; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBodyText() { return bodyText; } public void setBodyText(String bodyText) { this.bodyText = bodyText; } public List
getBodyPart() { return bodyPart; } public void setBodyPart(List
bodyPart) { this.bodyPart = bodyPart; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; }}
mail.properties
#SMTPmail.smtp.host=smtpa.hostmail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactorymail.smtp.ssl.enable=truemail.smtp.socketFactory.fallback=falsemail.smtp.port=465mail.transport.protocol=smtpsmail.smtp.socketFactory.port=465mail.smtp.auth=true#POP3mail.pop3s.host=pop3.hostmail.pop3.socketFactory.class=javax.net.ssl.SSLSocketFactorymail.pop3.ssl.enable=truemail.pop3.socketFactory.fallback=falsemail.pop3s.port=995mail.store.protocol=pop3smail.pop3.socketFactory.port=995mail.pop3s.auth=trueusername=abc@abc.compassword=passwordforwardTo=xyz@xyz.comlogFile=c:/mail.logjssecacerts=jssecacerts

转载于:https://my.oschina.net/l1z2g9/blog/176284

你可能感兴趣的文章
Android 日志级别总结
查看>>
生产环境部署NodeJs最佳实践
查看>>
2t3ik与ddgs挖矿病毒处理
查看>>
基于K8S部署fission函数即服务
查看>>
html备份
查看>>
阿里曾鸣:全球最值钱的互联网公司都做对了什么?
查看>>
千万不要嫁给程序猿,我是认真的
查看>>
刚拿百度offer回来,分享一份刚出炉的百度Java面试真题详解
查看>>
C语言之基本运算及自动类型转换和强制类型转换
查看>>
docker私有仓库管理系统harbor的部署使用
查看>>
centos 编译安装gcc8.1
查看>>
ICS Protocol Dissection
查看>>
Linux的DHCP服务配置
查看>>
我的友情链接
查看>>
【挨踢人物传】李晨光:兴趣铸就专业,努力决定成败
查看>>
横向ListView
查看>>
mysql主从同步操作
查看>>
隐藏自己的进程
查看>>
全国省市数据
查看>>
判断文件夹大小并复制到另一个地方
查看>>