android平台收发邮件教程

http://blog.sina.com.cn/s/blog_56e5b1410101lael.html


一、开发前准备

1、下载jar包,下载地址

http://code.google.com/p/javamail-android/downloads/list

additionnal.jar、mail.jar 和 activation.jar

2、在eclipse中新建一个android app工程

3、用鼠标将下载下来的三个jar包拖动到新建工程的lib文件加下,出现提示,选择copy

4、在新建的工程文件夹点右键属性,选择Java Build Path,右面选择libraries,点击右面的 Add JARs,选择那3个jar包,点击OK

5、打开工程的AndroidManifest.xml文件,加上

 <uses-permission android:name="android.permission.INTERNET" />

表示可以访问网络,并将android:minSdkVersion 设置为"11"

6、在主程序进行邮件操作前加上以下代码

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
        .detectDiskReads()  
        .detectDiskWrites()  
        .detectNetwork()
        .penaltyLog()  
        .build());  
 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
        .detectLeakedSqlLiteObjects()  
        .detectLeakedClosableObjects()  
        .penaltyLog()  
        .penaltyDeath()  
        .build());

主要原因是,android4.0以后的版本不允许在主程序中进行联网操作,否则会报如下错误

android.os.NetWorkOnMainException和android.os.NetWorkOnMainThreadException

二、收取邮件

提示:通过pop3方式收邮件,收取第一遍发现有邮件后,如果没有新的邮件产生,再次收取时会收不到任何邮件(也就是说得到的是NULL)。

1、在工程包内新建2个JAVA类,MailList.java和ReceiveMail.java,把以下代码拷贝进去

(1)MailList.java

--------------------------------------------------------------------------------------------

package 你的包名;

import java.util.*;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
public class MailList {
    private String host ; //pop3服务器
    private String user ; //邮箱
    private String password ; // 密码
   
    private static MailList instance;
    private List mailList;
    private HashMap serviceHashMap;
   
    public static MailList getInstance(){
     if(instance==null){
      instance=new MailList("pop.163.com","example@163.com","000000");
     }
     return instance;
    }
   
    public String getUpdateUrlStr() throws Exception{
     String urlStr=null;
     if(serviceHashMap==null){
      serviceHashMap=this.getServeHashMap();
     }
     if(serviceHashMap.get("update")==1){
      urlStr=mailList.get(1).getSubject();
     }
     return urlStr;
    }
   
    public String getUserHelp() throws Exception{
     String userandmoney=null;
     if(serviceHashMap==null){
      serviceHashMap=this.getServeHashMap();
     }
     if(serviceHashMap.get("userhelp")==1){
      userandmoney=mailList.get(3).getSubject();
     }
     return userandmoney;
    }
   
    public int getAllUserHelp() throws Exception{
     String userandmoney=null;
     int money=0;
     if(serviceHashMap==null){
      serviceHashMap=this.getServeHashMap();
     }
     if(serviceHashMap.get("userhelp")==1){
      userandmoney=mailList.get(3).getSubject();
     }
     if(userandmoney!=null && userandmoney.contains("all-user-100")){
      money=Integer.parseInt(userandmoney.substring(userandmoney.lastIndexOf("-"+1),
userandmoney.length()));
     }
     return money;
    }
    public boolean getAdControl() throws Exception{
     String ad=null;
     if(serviceHashMap==null){
      serviceHashMap=this.getServeHashMap();
     }
     if(serviceHashMap.get("adcontrol")==1){
      ad=mailList.get(2).getSubject();
     }
     if(ad.equals("ad=close")){
      return false;
     }
     return true;
    }
   
    public HashMap getServeHashMap() throws Exception{
     serviceHashMap=new HashMap();
     if(mailList==null){
      mailList=getAllMail("INBOX");
     }
     String serviceStr=mailList.get(0).getSubject();
     if(serviceStr.contains("update 1.0=true")){
      serviceHashMap.put("update", 1);
     }else if(serviceStr.contains("update 1.0=false")){
      serviceHashMap.put("update", 0);
     }
     if(serviceStr.contains("adcontrol 1.0=true")){
      serviceHashMap.put("adcontrol", 1);
     }else if(serviceStr.contains("adcontrol 1.0=false")){
      serviceHashMap.put("adcontrol", 0);
     }
     if(serviceStr.contains("userhelp 1.0=true")){
      serviceHashMap.put("userhelp", 1);
     }else if(serviceStr.contains("userhelp 1.0=false")){
      serviceHashMap.put("userhelp", 0);
     }
    
     return serviceHashMap;
    }
   
    public MailList(String popHost,String userAcount,String password){
        this.host=popHost;
        this.user=userAcount;
        this.password=password;
    }
   
   
    public List getAllMail(String folderName) throws MessagingException{
     List  mailList=new ArrayList();
      
      // 连接服务器
       Session session = Session.getDefaultInstance(
       System.getProperties(), null);
       Store store = session.getStore("pop3");
       store.connect(host,user, password);
       // 打开文件夹
       Folder folder = store.getFolder(folderName);
       folder.open(Folder.READ_ONLY);
        // 总的邮件数
       int mailCount = folder.getMessageCount();
       if (mailCount==0){
            folder.close(true);
            store.close();
            return null;
        }else{
            // 取得所有的邮件
            Message[] messages = folder.getMessages();
            for (int i = 0; i < messages.length; i++) {
                // 自定义的邮件对象
                ReceiveMail reciveMail=new ReceiveMail((MimeMessage)messages[i]);
                reciveMail.setDataFormat("yy年MM月dd日 HH:mm");// 邮件收信时间格式设定
                mailList.add(reciveMail);//添加到邮件列表中   
           }
            // 关闭文件夹
       //     folder.close(true);
      //      store.close();
                       // 返回获取到的邮件
           return mailList;
      }
    }
}
----------------------------------------------------------------------------------------------

(2)ReceiveMail.java

----------------------------------------------------------------------------------------------

package 你的包名;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
public class ReceiveMail {
    private MimeMessage mimeMessage = null;
    private StringBuffer mailContent = new StringBuffer();// 邮件内容
    private String dataFormat = "yy-MM-dd HH:mm";
   
    public ReceiveMail(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }
    // MimeMessage设定
    public void setMimeMessage(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }
   
   public String getFrom() throws MessagingException {
        InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
        String addr = address[0].getAddress();
        String name = address[0].getPersonal();
        if (addr == null) {
           addr = "";
        }
        if (name == null) {
            name = "";
        }
        String nameAddr = name + "<" + addr + ">";
       return nameAddr;
   }
  
    public String getMailAddress(String type) throws Exception {
        String mailAddr = "";
       String addType = type.toUpperCase();
        InternetAddress[] address = null;
        if (addType.equals("TO")) {
            address = (InternetAddress[]) mimeMessage
                    .getRecipients(Message.RecipientType.TO);
        } else if (addType.equals("CC")) {
            address = (InternetAddress[]) mimeMessage
                    .getRecipients(Message.RecipientType.CC);
        } else if (addType.equals("BCC")) {
            address = (InternetAddress[]) mimeMessage
                    .getRecipients(Message.RecipientType.BCC);
        } else {
            System.out.println("error type!");
            throw new Exception("Error emailaddr type!");
        }
        if (address != null) {
            for (int i = 0; i < address.length; i++) {
                String mailaddress = address[i].getAddress();
                if (mailaddress != null) {
                    mailaddress = MimeUtility.decodeText(mailaddress);
                } else {
                    mailaddress = "";
                }
                String name = address[i].getPersonal();
                if (name != null) {
                    name = MimeUtility.decodeText(name);
                } else {
                    name = "";
                }
                mailAddr = name + "<" + mailaddress + ">";
            }
        }
        return mailAddr;
    }
   
    public String getSubject() {
        String subject = "";
        try {
            subject = MimeUtility.decodeText(mimeMessage.getSubject());
            if (subject == null) {
                subject = "";
            }
        } catch (Exception e) {
        }
        return subject;
    }
   
    public String getSentData() throws MessagingException {
        Date sentdata = mimeMessage.getSentDate();
        if (sentdata!=null){
        SimpleDateFormat format = new SimpleDateFormat(dataFormat);
        return format.format(sentdata);
        }else{
            return "不清楚";
        }
       
    }
   
    public String getMailContent() throws Exception {
       compileMailContent((Part)mimeMessage);
       return mailContent.toString();
   }
   
    public void compileMailContent(Part part) throws Exception {
        String contentType = part.getContentType();
        int nameIndex = contentType.indexOf("name");
        boolean connName = false;
        if (nameIndex != -1) {
            connName = true;
        }
        if (part.isMimeType("text/plain") && !connName) {
            mailContent.append((String) part.getContent());
        } else if (part.isMimeType("text/html") && !connName) {
            mailContent.append((String) part.getContent());
        } else if (part.isMimeType("multipart
    public boolean getReplySign() throws MessagingException {
        boolean replySign = false;
        String needreply[] = mimeMessage
                .getHeader("Disposition-Notification-To");
        if (needreply != null) {
            replySign = true;
        }
        return replySign;
    }
   
    public String getMessageID() throws MessagingException {
        return mimeMessage.getMessageID();
    }
   
    public boolean isNew() throws MessagingException {
        boolean isnew = false;
        Flags flags = ((Message) mimeMessage).getFlags();
        Flags.Flag[] flag = flags.getSystemFlags();
        for (int i = 0; i < flag.length; i++) {
            if (flag[i] == Flags.Flag.SEEN) {
                isnew = true;
                break;
            }
        }
        return isnew;
    }
    public void setMailContent(StringBuffer mailContent) {
        this.mailContent = mailContent;
    }
   
   
    public void setDataFormat(String dataFormat) {
        this.dataFormat = dataFormat;
    }
}

----------------------------------------------------------------------------------------------

2、程序中实现接收邮件代码

private List<ReceiveMail> mails;

MailList mailList=new MailList(pop服务器地址,用户名,密码);

try{
   mails=mailList.getAllMail("INBOX");//如果是NULL,而且不抛异常,说明没有新邮件了

   if(mails!=null){

   ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

   for(int i=0;i<mails.size();i++){

       ReceiveMail reciveMail=mails.get(i);    
       String mail_from=reciveMail.getFrom();//发件人邮箱
       String mail_date=reciveMail.getSentData();//发件日期
       String mail_subject=reciveMail.getSubject();//标题

       //.......其他的信息都可以取到了。

       listItem.add(map);  

    }

   }

}catch(MessagingException e){
   e.printStackTrace(); 
  }

三、发送邮件的代码

1、新建一个JAVA类,MailSender.java,代码如下

----------------------------------------------------------------------------------------------

package 你的包名;

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender{
    private String host;
    private String username;
    private String password;
// 下面是一个实例   
   
   
    public MailSender(String host,String username,String password){
            this.host = host;
            this.username = username;
            this.password = password;
    }
   
    public void send(String mailTo,String mailSubject,String mailBody) throws Exception{
            this.send(mailTo, mailSubject, mailBody, null);
    }
   
    public void send(String mailTo,String mailSubject,String mailBody,String personalName) throws
Exception{
        try{
            Properties props=new Properties();
            Authenticator auth = new Email_Autherticator();
            //进行邮件服务器用户认证
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getInstance(props, auth);
           // Session session = Session.getDefaultInstance(props, auth);
            //设置session,和邮件服务器进行通讯。
            MimeMessage message = new MimeMessage(session);
            //message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
            message.setSubject(mailSubject); // 设置邮件主题
            message.setText(mailBody); // 设置邮件正文
            message.setSentDate(new Date()); // 设置邮件发送日期
            Address address = new InternetAddress(username, personalName);
            message.setFrom(address); // 设置邮件发送者的地址
            Address toAddress = new InternetAddress(mailTo); // 设置邮件接收方的地址
            message.addRecipient(Message.RecipientType.TO, toAddress);
            Transport.send(message); // 发送邮件
         }catch (Exception ex){
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        }
    }
   
    public class Email_Autherticator extends Authenticator{
        public PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication(username, password);
        }
   }
}

 

----------------------------------------------------------------------------------------------

2、程序中实现发送邮件的代码

 

 MailSender mailSender=new MailSender(发送邮件服务器,发送者邮箱,发送者密码);
 String mailTo=接收邮件方的邮箱;
 String mailSubject="邮件标题";
 String mailBody="邮件内容";
 try{
  mailSender.send(mailTo, mailSubject, mailBody);
 }catch(Exception e){
  e.printStackTrace();
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值