---
title: "JavaMail的发送和收取"
author: "sanshi"
date: "2007-05-02T19:55:52Z"
tags: []
slug: "javamail"
draft: false
lastmod: "2007-05-02T19:55:52Z"
id: 76674
url: "https://sanshi.iteye.com/blog/76674"
---

邮件的发送：  
     import   javax.mail.\*；  
     importj   avax.mail.internet.\*；  
      import   javax.activation.\*；  
     import   java.util.\*；  
      
  public static void main(String\[] argv){  
  Properties   props   =   new   Properties();    
  Session   sendMailSession;    
  Store   store;    
  Transport   transport;    
  sendMailSession   =   Session.getInstance(props,   null);    
  props.put("mail.smtp.host",   "smtp.163.com");     //put 属性改成了setProperties

  props.put("mail.smtp.auth",   "true");     //add    
  Message   newMessage   =   new   MimeMessage(sendMailSession);    
  newMessage.setFrom(new   InternetAddress("guolei30@163.com"));    
  newMessage.setRecipient(Message.RecipientType.TO,   new   InternetAddress("guolei30@163.com"));    
  newMessage.setSubject("subject1");    
  newMessage.setSentDate(new  Date());    
  newMessage.setText("text");    
  transport   =   sendMailSession.getTransport("smtp");    
  newMessage.saveChanges();    
  transport.connect("smtp.163.com","guolei30","\*\*\*\*\*\*\*.");    
  transport.sendMessage(newMessage,newMessage.getRecipients(Message.RecipientType.TO));     //modify    
  //transport.send(newMessage);    
  transport.close();     
    catch(SendFailedException   e)    
  {    
      out.println(e.toString());    
  }    
  catch(MessagingException   m)    
  {    
  out.println(m.toString());    
  }     
    邮件的收取：  
   import   javax.mail.\*；  
     importj   avax.mail.internet.\*；  
      import   javax.activation.\*；  
     import   java.util.\*；

Properties prop=new Properties();  
    prop.setProperty("mail.pop3.host","pop.163.com");  
    Session MailSession=Session.getDefaultInstance(prop);  
    Store store=MailSession.getStore("pop3");  
   store.connect("pop.163.com","guolei30","\*\*\*\*\*\*\*.");  
   Folder inbox=store.getDefaultFolder().getFolder("INBOX");  
   inbox.open(Folder.READ\_ONLY);

    Message\[] msg=inbox.getMessages();

   // FetchProfile profile=new FetchProfile();  
   // profile.add(FetchProfile.Item.ENVELOPE);  
    //inbox.fetch(msg,profile);  
   out.println("邮件主题:"+msg\[2].getSubject());  
  out.println("邮件作者:"+msg\[2].getFrom()\[0].toString());  
   out.println("发送日期:"+msg\[2].getSentDate());  
    out.println("邮件内容:"+msg\[2].getContent());  
inbox.close(false);  
store.close();  
//处理Multipart邮件，包括了保存附件的功能  
　　public void handleMultipart(Message msg) throws Exception  
　　{  
　　String disposition;  
　　BodyPart part;  
　　  
　　Multipart mp=(Multipart)msg.getContent();  
　　int mpCount=mp.getCount();