java mail 收发邮件

java mail 收发邮件


1.发件

2.收件


1.发件

package base.util; /* Some SMTP servers require a username and password authentication before you can use their Server for Sending mail. This is most common with couple of ISP's who provide SMTP Address to Send Mail. This Program gives any example on how to do SMTP Authentication (User and Password verification) This is a free source code and is provided as it is without any warranties and it can be used in any your code for free. Author : Sudhir Ancha */ import javax.mail.*; import javax.mail.internet.*; import java.util.*; import java.io.*; public class SendMailHelper { // defalt config private static String SMTP_HOST_NAME = "smtp.163.com"; private static String SMTP_AUTH_USER = "XXX@163.com"; private static String SMTP_AUTH_PWD = "XXX"; private static String emailMsgTxt = "text"; private static String emailSubjectTxt = "Subject"; private static String emailFromAddress = "XXX@163.com"; // Add List of Email address to who email needs to be sent to private static String[] emailList = { "emaillist" }; public static void main(String args[]) throws Exception { SendMailHelper smtpMailSender = new SendMailHelper(); smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress); System.out.println("Sucessfully Sent mail to All Users"); } public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException { boolean debug = false; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(); Session session = Session.getDefaultInstance(props, auth); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); Transport.send(msg); } /** * SimpleAuthenticator is used to do simple authentication * when the SMTP server requires it. */ private class SMTPAuthenticator extends javax.mail.Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username = SMTP_AUTH_USER; String password = SMTP_AUTH_PWD; return new PasswordAuthentication(username, password); } } public static String getSMTP_HOST_NAME() { return SMTP_HOST_NAME; } public static void setSMTP_HOST_NAME(String smtp_host_name) { SMTP_HOST_NAME = smtp_host_name; } public static String getSMTP_AUTH_USER() { return SMTP_AUTH_USER; } public static void setSMTP_AUTH_USER(String smtp_auth_user) { SMTP_AUTH_USER = smtp_auth_user; } public static String getSMTP_AUTH_PWD() { return SMTP_AUTH_PWD; } public static void setSMTP_AUTH_PWD(String smtp_auth_pwd) { SMTP_AUTH_PWD = smtp_auth_pwd; } public static String getEmailMsgTxt() { return emailMsgTxt; } public static void setEmailMsgTxt(String emailMsgTxt) { SendMailHelper.emailMsgTxt = emailMsgTxt; } public static String getEmailSubjectTxt() { return emailSubjectTxt; } public static void setEmailSubjectTxt(String emailSubjectTxt) { SendMailHelper.emailSubjectTxt = emailSubjectTxt; } public static String getEmailFromAddress() { return emailFromAddress; } public static void setEmailFromAddress(String emailFromAddress) { SendMailHelper.emailFromAddress = emailFromAddress; } public static String[] getEmailList() { return emailList; } public static void setEmailList(String[] emailList) { SendMailHelper.emailList = emailList; } }

2.收件

暂时不能支持yahoo邮箱,参考这里http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail

Q: How do I access Yahoo! Mail with JavaMail? A: JavaMail 1.4 is capable of sending and reading messages using Yahoo! Mail Plus. All that's required is to properly configure JavaMail. I'll illustrate the proper configuration using the demo programs that come with JavaMail - msgshow.java and smtpsend.java. Note that free Yahoo! Mail accounts do not allow POP3 or SMTP access. You must purchase a Yahoo! Mail Plus account to get POP3 and SMTP access. Let's assume your Yahoo! Mail username is "user@yahoo.com" and your password is "passwd". To read mail from your Yahoo! Mail Inbox, invoke msgshow as follows: java msgshow -D -T pop3s -H pop.mail.yahoo.com -U user -P passwd By reading the msgshow.java source code, you can see how these command line arguments are used in the JavaMail API. You should first try using msgshow as shown above, and once that's working move on to writing and configuring your own program to use Yahoo! Mail. The code fragment shown above for connecting to Gmail will also work for connecting to Yahoo! Mail by simply changing the host name. To send a message through Yahoo! Mail, invoke smtpsend as follows: java -Dmail.smtps.host=smtp.mail.yahoo.com -Dmail.smtps.auth=true smtpsend -d -S -M smtp.mail.yahoo.com -U user -P passwd -A user@yahoo.com (Note that I split the command over two lines for display, but you should type it on one line.) A bug in older versions of the smtpsend command causes it to set the incorrect properties when using the -S (SSL) option, so we work around that bug by setting them on the command line. The smtpsend program uses the System properties when creating the JavaMail Session, so the properties set on the command line will be available to the JavaMail Session. The smtpsend program will prompt for a subject and message body text. End the message body with ^D on UNIX or ^Z on Windows. Again, you can read the smtpsend.java source code to see how the command line arguments are used in the JavaMail API. The code fragment shown above for connecting to Gmail will also work for connecting to Yahoo! Mail by simply changing the host name. There is, of course, more than one way to use the JavaMail API to accomplish the same goal. This should help you understand the essential configuration parameters necessary to use Yahoo! Mail. Also see the Yahoo! Mail help page Accessing Yahoo! Mail via POP

实现代码:

Attachment.java类:

package com.runstate.mailpage; class Attachment { private String contenttype; private String filename; private byte[] content; private String contentid; public String getContenttype() { return contenttype; } public void setContenttype(String contenttype) { this.contenttype = contenttype; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getContentid() { return contentid; } public void setContentid(String contentid) { this.contentid = contentid; } }

Renderable接口:

package com.runstate.mailpage; public interface Renderable { Attachment getAttachment(int i); int getAttachmentCount(); String getBodytext(); String getSubject(); }

RenderableMessage类:

package com.runstate.mailpage; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.CharBuffer; import java.util.ArrayList; import javax.mail.*; public class RenderableMessage implements Renderable { private String subject; private String bodytext; ArrayList attachments; /** Creates a new instance of RenderableMessage */ public RenderableMessage(Message m) throws MessagingException,IOException { subject=m.getSubject().substring("test".length()); attachments=new ArrayList(); extractPart(m); } private void extractPart(final Part part) throws MessagingException, IOException { if(part.getContent() instanceof Multipart) { Multipart mp=(Multipart)part.getContent(); for(int i=0;i<mp.getCount();i++) { extractPart(mp.getBodyPart(i)); } return; } if(part.getContentType().startsWith("text/html")) { if(bodytext==null) { bodytext=(String)part.getContent(); } else { bodytext=bodytext+"<HR/>"+(String)part.getContent(); } } else if(!part.getContentType().startsWith("text/plain")) { Attachment attachment=new Attachment(); attachment.setContenttype(part.getContentType()); attachment.setFilename(part.getFileName()); InputStream in=part.getInputStream(); ByteArrayOutputStream bos=new ByteArrayOutputStream(); byte[] buffer=new byte[8192]; int count=0; while((count=in.read(buffer))>=0) bos.write(buffer,0,count); in.close(); attachment.setContent(bos.toByteArray()); attachments.add(attachment); } } public String getSubject() { return subject; } public String getBodytext() { return bodytext; } public int getAttachmentCount() { if(attachments==null) return 0; return attachments.size(); } public Attachment getAttachment(int i) { return (Attachment)attachments.get(i); } }

RenderablePlainText类:

package com.runstate.mailpage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.mail.Message; import javax.mail.MessagingException; public class RenderablePlainText implements Renderable { String bodytext; String subject; /** Creates a new instance of RenderablePlainText */ public RenderablePlainText(Message message) throws MessagingException, IOException { subject=message.getSubject().substring("MailPage:".length()); bodytext=(String)message.getContent(); } public Attachment getAttachment(int i) { return null; } public int getAttachmentCount() { return 0; } public String getBodytext() { return "<PRE>"+bodytext+"</PRE>"; } public String getSubject() { return subject; } }

MailRetriever类:

package com.runstate.mailpage; import java.io.IOException; import java.security.Security; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import javax.mail.Authenticator; import javax.mail.FetchProfile; 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.Provider; import javax.mail.Flags; public class MailRetriever { private String emailuser; private String emailpassword; private String emailserver; private String emailprovider; // 构造函数 public MailRetriever(String emailuser,String emailpassword,String emailserver,String emailprovider) { this.emailuser=emailuser; this.emailpassword=emailpassword; this.emailserver=emailserver; this.emailprovider=emailprovider; } // 得到所有的邮件 public Message[] retrieveAllMailMessage() throws Exception { Session session; Store store=null; Folder folder=null; Folder inboxfolder=null; Properties props=System.getProperties(); props.setProperty("mail.pop3s.rsetbeforequit","true"); props.setProperty("mail.pop3.rsetbeforequit","true"); session=Session.getInstance(props,null); // 打印出错误信息 session.setDebug(true); store=session.getStore(emailprovider); store.connect(emailserver, emailuser, emailpassword); folder=store.getFolder("INBOX"); if(folder==null) throw new Exception("No default folder"); //inboxfolder=folder.getFolder("INBOX"); inboxfolder = folder; if(inboxfolder==null) throw new Exception("No INBOX"); inboxfolder.open(Folder.READ_WRITE); Message[] msgs = inboxfolder.getMessages(); for(int i = 0; i < msgs.length; ++i) { System.out.println("################################"); if (msgs[i] != null) { System.out.println("邮件标题:" + msgs[i].getSubject()); System.out.println("邮件发送者:" + msgs[i].getFrom()); System.out.println("邮件发送时间:" + msgs[i].getSentDate()); System.out.println("邮件正文:" + ((msgs[i].getContent() == null) ? "没有正文" : msgs[i].getContent())); RenderableMessage render = new RenderableMessage(msgs[i]); int count = new RenderableMessage(msgs[i]) .getAttachmentCount(); System.out.println("附件数量:" + count); // 得到附件内容,如果存在附件的话,可以使用Attachement来读取 // 附件的内容 if (count > 0) { // 读取附件 for (int j = 0; j < count; ++j) { Attachment attachment = render.getAttachment(j); System.out.println("附件类型:" + attachment.getContenttype()); System.out.println("附件名称:" + attachment.getFilename()); } } } } return msgs; } // 得到未读邮件 public List retrieveAllUnreadMessage() throws Exception { List unreadMessages = new ArrayList(); Session session; Store store=null; Folder folder=null; Folder inboxfolder=null; Properties props=System.getProperties(); props.setProperty("mail.pop3s.rsetbeforequit","true"); props.setProperty("mail.pop3.rsetbeforequit","true"); session=Session.getInstance(props,null); // 打印出错误信息 //session.setDebug(true); store=session.getStore(emailprovider); store.connect(emailserver, emailuser, emailpassword); folder=store.getFolder("INBOX"); if(folder==null) throw new Exception("No default folder"); //inboxfolder=folder.getFolder("INBOX"); inboxfolder = folder; if(inboxfolder==null) throw new Exception("No INBOX"); inboxfolder.open(Folder.READ_WRITE); Message[] msgs = inboxfolder.getMessages(); if (msgs.length == 0) { System.out.println("No Message to Read"); } else { System.out.println("Total Messages Found:" + msgs.length + ""); } // Loop over all of the messages for (int messageNumber = 0; messageNumber < msgs.length; messageNumber++) { Message message = msgs[messageNumber]; Flags flags = message.getFlags(); if (!message.isSet(Flags.Flag.SEEN) && !message.isSet(Flags.Flag.ANSWERED)) { unreadMessages.add(message); } } return unreadMessages; } //方法中存在不足 public void getMail() { Session session; Store store=null; Folder folder=null; Folder inboxfolder=null; Properties props=System.getProperties(); props.setProperty("mail.pop3s.rsetbeforequit","true"); props.setProperty("mail.pop3.rsetbeforequit","true"); session=Session.getInstance(props,null); //session.setDebug(true); try { store=session.getStore(emailprovider); store.connect(emailserver, emailuser, emailpassword); folder=store.getFolder("INBOX"); if(folder==null) throw new Exception("No default folder"); //inboxfolder=folder.getFolder("INBOX"); inboxfolder = folder; if(inboxfolder==null) throw new Exception("No INBOX"); inboxfolder.open(Folder.READ_ONLY); Message[] msgs=inboxfolder.getMessages(); FetchProfile fp=new FetchProfile(); fp.add("Subject"); inboxfolder.fetch(msgs,fp); for(int j=msgs.length-1;j>=0;j--) { // System.out.println("/" + msgs[j].getSubject()); if(msgs[j].getSubject().startsWith("test")) { setLatestMessage(msgs[j]); break; } } inboxfolder.close(false); store.close(); } catch (NoSuchProviderException ex) { ex.printStackTrace(); } catch (MessagingException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if(store!=null) store.close(); } catch (MessagingException ex) { ex.printStackTrace(); } } } // 方法中存在不足之处 public Renderable getLatestMessage() { return latestMessage; } private Renderable latestMessage; void setLatestMessage(Message message) { if(message==null) { latestMessage=null; return; } try { if(message.getContentType().startsWith("text/plain")) { latestMessage=new RenderablePlainText(message); } else { latestMessage=new RenderableMessage(message); } } catch (MessagingException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { //MailRetriever mr=new MailRetriever(args[0],args[1],args[2],args[3]); // 设置参数 //###################################################### // 设置参数 //#################################################### // 这里需要注意的是这个方法是没办法收取yahoo的邮箱的 String emailuser = "xuqianghit@sohu.com"; // 用户名 String emailpassword = "helloworld"; // 密码 String emailserver = "smtp.sohu.com"; // 邮件服务器名称 String emailprovider = "imap"; // 使用协议imap, pop3等 MailRetriever mr = new MailRetriever(emailuser, emailpassword, emailserver, emailprovider); try { // 顺序 //System.out.println("未读邮件有:" + mr.retrieveAllUnreadMessage().toArray().length); if(null != mr) mr.retrieveAllMailMessage(); } catch (Exception e) { e.printStackTrace(); } /* mr.getMail(); Renderable msg=mr.getLatestMessage(); if(msg==null) { System.out.println("No valid messages in the mail account"); } else { System.out.println("Subject:"+msg.getSubject()); System.out.println("Body Text:"+msg.getBodytext()); System.out.println(msg.getAttachmentCount()+" attachments"); for(int i=0;i<msg.getAttachmentCount();i++) { Attachment at=msg.getAttachment(i); System.out.println(at.getFilename()+" "+at.getContent().length+" bytes of ("+at.getContenttype()+")"); } } */ } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值