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()+")");
            
            }
        }
        
        */
    }
}

转载于:https://www.cnblogs.com/xuqiang/archive/2010/12/07/1953369.html

java mail 收发邮件相关推荐

  1. 如何配置SQL AgentMail与SQL Mail收发邮件

      如何配置SQL AgentMail与SQL Mail收发邮件 SQL AgentMail是负责在警告被触发时或是在预定作业成功或失败时发送通告的电子邮件服务:SQL Mail 是用来处理数据库应用 ...

  2. java velocity 邮件_邮件集成java mail + 读取邮件模板

    项目做异地登录提醒功能,通过java mail发送邮件.读取邮件模板sendMail.vm文件. 1.邮件发送 import java.io.StringWriter; import java.uti ...

  3. 关于java mail 发邮件的问题总结(转)

    今天项目中有需要用到java mail发送邮件的功能,在网上找到相关代码,代码如下: import java.io.IOException; import java.util.Properties; ...

  4. Spring Java Mail发邮件

    今天测试了下spring的发邮件的功能 下上代码 在说遇到的问题 首先在applicationContext.xml配置邮件信息 <bean id="mailSender" ...

  5. 邮件集成java mail + 读取邮件模板

    项目做异地登录提醒功能,通过java mail发送邮件.读取邮件模板sendMail.vm文件. 1.邮件发送 import java.io.StringWriter; import java.uti ...

  6. Java mail接收邮件 回复邮件 转发邮件

    下面的代码在很多别的博客上都有,我只是copy过来学习了下,并且做了少许的修改,但大多数用的都是POP3协议去接收邮件,如果你实际验证过就应该会发现至少从昨天开始是不能获取邮件的内容的,所以需要用IM ...

  7. Java Mail(发邮件)

    邮箱相关协议介绍: 参考博客:https://blog.csdn.net/suhuaiqiang_janlay/article/details/78765613 简单邮件发送案例: import or ...

  8. java mail 保存邮件_JavaMail保存为草稿邮件

    package 草稿测试; import java.util.Date; import java.util.Properties; import javax.mail.*; import javax. ...

  9. java mail 503_邮件配置报503错误,发送失败

    $row 不是数组 你这个版本应该不是最新版,试着后台打印一下$row的值 这个最新版本的代码/** * 发送测试邮件 * @internal */ public function emailtest ...

最新文章

  1. C++11中nullptr的使用
  2. ​GEB:焦硕等发表生态位的系统发育保守性决定土壤古菌地理格局
  3. jittor和pytorch生成网络对比之unit
  4. LA3989女士的选择
  5. Java机器学习库ML之八关于模型迭代训练的试验
  6. 图论--欧拉回路(模板)
  7. Mac安装svn客户端
  8. 三维场景 WGS84 和街景(百度街景,腾讯街景,google街景,orbitgt街景)联动
  9. 使用vue-pdf-signature实现pdf预览
  10. java get中文乱码怎么解决_java中get请求中文乱码怎么办?
  11. 虚拟电厂 3D 可视化,节能减排绿色发展
  12. java中lifo的数组_Java 实现下压(LIFO)栈
  13. 深入浅出 Docker
  14. 软著申请时提取60页代码shell命令解析
  15. Chapter4.2:根轨迹法
  16. 汽车ABS系统-第一周作业
  17. numpy基础篇-简单入门教程4
  18. SaaS-初识SaaS
  19. 不止是刷题——leetcode笑死人的评论合集,独乐乐不如众乐乐~~
  20. 关于《匀速贝塞尔曲线运动的实现》的过程推算

热门文章

  1. PowerDesigner生成的建表脚本中如何把对象的双引号去掉
  2. kotlin环境配置
  3. Java使用IntelliJ IDEA创建控制台程序并通过JDBC连接到数据库
  4. 牛客竞赛,GDDU第十届文远知行杯新生程序设计竞赛,摸鱼记(BDEIKL题解,补G,ACFHJ)
  5. 【编辑器】VSCode配置C++编译
  6. 2021年文山州一中高考成绩查询,云南文山第一中学2021年录取分数线
  7. js实现kmp算法_搜索算法 与 随机算法 (JS实现)
  8. JavaScript函数内可以调用另一个函数(3)
  9. hdu 4417 树状数组查询区间不是1到n时需要转换,例[0,5]变成[1,6]
  10. 通过键盘事件执行查询与回填数据