Javamail使用gmail发邮件

    周末找了几个关于用Javamail发送邮件的文章,实践了一个成功的,这里整理了一下,并略作修改,以备参考。

一、基本思路

     1.Session对象设置邮件服务器和端口之类的属性,建立会话

     2.MimeMultipart对象装载邮件内容和附件等

     3.Message对象邮件基本信息,如发件人、收件人等

     4.Transport对象负责发送邮件

二、过程

    1、新建一个andriod应用项目,带blank activity

    2、将Javamail的三个包copy到此项目的libs目录:activation.jar、additionnal.jar、mail.jar,项目里refresh下就可以看到了

    3、 给AndroidManifest.xml配置,放到application节点前面即可

    4、实现EmailSender类

 public class EmailSender {
 private Properties properties;
 private Session session;
 private Message message;
 private MimeMultipart multipart;

 private String mailhost;
 public EmailSender() {
  super();
  this.properties = new Properties();
 }
 public void setProperties(String host,String port){
  this.mailhost = host;
  //地址
  this.properties.put("mail.smtp.host",host);
  //端口号
  this.properties.put("mail.smtp.port",port);
  //是否验证
  this.properties.put("mail.smtp.auth","true");
  
  //下面三个属性gmail发送要有,否则出错
  this.properties.put("mail.smtp.socketFactory.port", port);  
  this.properties.put("mail.smtp.socketFactory.class",  
                "javax.net.ssl.SSLSocketFactory");  
  this.properties.put("mail.smtp.socketFactory.fallback", "false");
       
  this.session=Session.getInstance(properties);
  this.message = new MimeMessage(session);
  this.multipart = new MimeMultipart("mixed");
 }
 /**
  * 设置收件人
  * @param receiver
  * @throws MessagingException
  */
 public void setReceiver(String[] receiver) throws MessagingException{
  Address[] address = new InternetAddress[receiver.length];
  for(int i=0;i    address[i] = new InternetAddress(receiver[i]);
  }
  this.message.setRecipients(Message.RecipientType.TO, address);
 }
 /**
  * 设置邮件
  * @param from 来源
  * @param title 标题
  * @param content 内容
  * @throws AddressException
  * @throws MessagingException
  */
 public void setMessage(String from,String title,String content) throws AddressException, MessagingException{
  this.message.setFrom(new InternetAddress(from));
  this.message.setSubject(title);
  //纯文本的话用setText()就行,不过有附件就显示不出来内容了
  MimeBodyPart textBody = new MimeBodyPart();
  textBody.setContent(content,"text/html;charset=gbk");
  this.multipart.addBodyPart(textBody);
 }
 /**
  * 添加附件
  * @param filePaths 文件路径
  * @throws MessagingException
  */
 public void addAttachment(String[] filePaths) throws MessagingException{
  for(int i=0;i   {
   File afile = new File(filePaths[i]);
   if(!afile.exists())
   {
    continue;
   }
   FileDataSource fileDataSource = new FileDataSource(afile);
   DataHandler dataHandler = new DataHandler(fileDataSource);
   MimeBodyPart mimeBodyPart = new MimeBodyPart();
   mimeBodyPart.setDataHandler(dataHandler);
   mimeBodyPart.setFileName(fileDataSource.getName());
   this.multipart.addBodyPart(mimeBodyPart);
  }
 }
 /**
  * 发送邮件
  * @param account 账户名
  * @param pwd 密码
  * @throws MessagingException
  */
 public void sendEmail(String account,String pwd) throws MessagingException{
  //发送时间
  this.message.setSentDate(new Date());
  //发送的内容,文本和附件
  this.message.setContent(this.multipart);
  this.message.saveChanges();
  //创建邮件发送对象,并指定其使用SMTP协议发送邮件 
  Transport transport=session.getTransport("smtp"); 
  //登录邮箱 
  transport.connect(this.mailhost,account,pwd); 
  //发送邮件
  transport.sendMessage(message, message.getAllRecipients());
  //关闭连接
  transport.close();
 }
 
}

 

5、MainActivity的onCreate中起一个线程,用EmailSender发邮件

      //sdcard路径

       if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = Environment.getExternalStorageDirectory().getPath();
        }
       
        //耗时操作要起线程
        new Thread(new Runnable() {

   @Override
   public void run() {
    try {
     EmailSender sender = new EmailSender();
     //设置服务器地址和端口,gmail用465端口,其他邮件服务器端口一般是25
     sender.setProperties("smtp.gmail.com", "465");
     //分别设置发件人,邮件标题和文本内容
     sender.setMessage("[email protected]", "EmailSender=test222", "Java Mail !test");
     //设置收件人
     sender.setReceiver(new String[]{"[email protected]"});
     //添加多个附件
     String[] attach = new String[]{path+"/DSC_1618.JPG",path+"/Vlog.xml"};
     if(attach.length>0){
      sender.addAttachment(attach);
     }
     //发送邮件
     sender.sendEmail("[email protected]", "your password");
    } catch (AddressException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }).start();


 

 

你可能感兴趣的:(Javamail使用gmail发邮件)