电子邮件使用Java邮件API中的机器人附件

电子邮件使用Java邮件API中的机器人附件

本文介绍了电子邮件使用Java邮件API中的机器人附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始与Android,这是我的第一个程序。

这是我的code样子。我可以发送电子邮件(背景)在使用本code,但无法附加文件与作为电子邮件附件。我已在mainfest.xml许可

请让我知道我在做什么错的,什么需要落实。

任何帮助是非常AP preciated。

 进口java.net.Authenticator中;
进口java.util.Date;
进口java.util.Properties;
进口javax.activati​​on.CommandMap;
进口的javax.activati​​on.DataHandler;
进口javax.activati​​on.DataSource;
进口javax.activati​​on.FileDataSource;
进口javax.activati​​on.MailcapCommandMap;
进口javax.mail.BodyPart;
进口javax.mail.Message;
进口javax.mail.MessagingException的;
进口javax.mail.Multipart;
进口javax.mail.PasswordAut​​hentication;
进口javax.mail.Session的;
进口javax.mail.Transport;
进口javax.mail.internet.InternetAddress;
进口javax.mail.internet.MimeBodyPart;
进口的javax.mail.internet.MimeMessage;
进口javax.mail.internet.MimeMultipart;

进口android.annotation.Sup pressLint;


公共类GMailSender扩展javax.mail.Authenticator {
  私人字符串_user;
  私人字符串_pass;

  私有String [_to]
  私人字符串_from;

  私人字符串_port;
  私人字符串_sport;

  私人字符串_host;

  私人字符串_subject;
  私人字符串_body;

  私人布尔_auth;

  私人布尔_debuggable;

  私人多部分_multipart;


  公共GMailSender(){
    _host =smtp.gmail.com;
    _port =465;
    _sport =465;

    _user =;
    _pass =;
    _from =;
    _subject =;
    _body =;

    _debuggable = FALSE;
    _auth = TRUE;

    _multipart =新MimeMultipart的();

     支持MailcapCommandMap MC =(支持MailcapCommandMap)CommandMap.getDefaultCommandMap();
    mc.addMailcap(text / html的;;的X Java的内容处理器= com.sun.mail.handlers.text_html);
    mc.addMailcap(文/ XML ;;的X Java的内容处理器= com.sun.mail.handlers.text_xml);
    mc.addMailcap(text / plain的;;的X Java的内容处理器= com.sun.mail.handlers.text_plain);
    mc.addMailcap(多部分/ * ;;的X Java的内容处理器= com.sun.mail.handlers.multipart_mixed);
    mc.addMailcap(信息/ RFC822 ;;的X Java的内容处理器= com.sun.mail.handlers.message_rfc822);
    CommandMap.setDefaultCommandMap(MC);
  }

  公共GMailSender(用户字符串,字符串通){
    本();

    _user =用户;
    _pass =通;
  }

  公共布尔发送(字符串,从,字符串主题字符串,字符串文本){
        回送(新的String [] {}来,发件人,主题,正文);
    }
    公共布尔发送(字符串[]到,从,字符串主题字符串,字符串文本){
        属性道具=新特性();
        props.put(mail.smtp.auth,真);
        props.put(mail.smtp.host,_host);
        props.put(mail.smtp.user,_user);
        props.put(mail.smtp.port,_port);
        props.put(mail.smtp.password,_pass);
        props.put(mail.smtp.socketFactory.port,_port);
        props.put(mail.smtp.socketFactory.class,javax.net.ssl​​.SSLSocketFactory);
        props.put(mail.smtp.socketFactory.fallback,假);

        会话会话= Session.getInstance(道具,这一点);

        尝试 {
            消息消息=新的MimeMessage(会议);
            message.setFrom(新网际(从));
            网际[] addressTo =新的网际[to.length]
            的for(int i = 0; I< to.length;我++){
                addressTo [我] =新的网际(在[I]);
            }
            message.setRecipients(Message.RecipientType.TO,addressTo);
            message.setSubject(学科);
            message.setText(文本);
            Transport.send(消息);
        }赶上(MessagingException E){
            e.printStackTrace();
            返回false;
        }
        返回true;
    }


    公共无效addAttachment(字符串文件名)抛出异常{
    BodyPart的messageBodyPart =新MimeBodyPart();
    数据源源=新FileDataSource(文件名);
    messageBodyPart.setDataHandler(新的DataHandler(源));
    messageBodyPart.setFileName(文件名);
    _multipart.addBodyPart(messageBodyPart);
  }

  @覆盖
  公共Password验证的getPasswordAut​​hentication(){
    返回新的PasswordAut​​hentication(_user,_pass);
  }

  私人性质_setProperties(){
    属性道具=新特性();
    props.put(mail.smtp.host,_host);
    如果(_debuggable){
      props.put(mail.debug,真);
    }
    如果(_auth){
      props.put(mail.smtp.auth,真);
    }
    props.put(mail.smtp.port,_port);
    props.put(mail.smtp.socketFactory.port,_sport);
    props.put(mail.smtp.socketFactory.class,javax.net.ssl​​.SSLSocketFactory);
    props.put(mail.smtp.socketFactory.fallback,假);
    返回道具;
  }
  // getter和setter
  公共字符串getBody(){
    返回_body;
  }
  公共无效setBody(字符串_body){
    this._body = _body;
  }
  //更多的getter和setter的... ..
}
 

和如何我打电话它在我的活动

 进口android.app.Activity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.text.format.Time;
进口android.util.Log;

公共类mailActivity延伸活动{
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        新PostTask()执行()。

        完();
     }

    公共类PostTask扩展的AsyncTask<字符串,太虚,字符串> {
        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            Log.d(doInBackground,你是在做背景......);

            字符串的文件路径=/storage/sdcard0/Bluetooth/2012.jpg;

            现在时间=新时代();
            now.setToNow();
            GMailSender发件人=新GMailSender([email protected],XXX.Password);
            尝试 {
                    sender.addAttachment(/存储/ sdcard0 /蓝牙/ 2012.jpg);
                    sender.send([email protected][email protected],沉默的邮件:+ now.format(%D-%M-%Y%H:%M) 这封电子邮件是发送默默在后台);

            赶上(例外五){
                Log.e(doInBackground,邮件异常...);
                Log.e(doInBackground,异常:+ e.toString());
                }
            Log.d(doInBackground,你完成了做背景......);
            返回null;
        }
    }
}
 

解决方案

 包com.mail.example;

进口java.util.Properties;

进口javax.activati​​on.CommandMap;
进口的javax.activati​​on.DataHandler;
进口javax.activati​​on.DataSource;
进口javax.activati​​on.FileDataSource;
进口javax.activati​​on.MailcapCommandMap;
进口javax.mail.BodyPart;
进口javax.mail.Message;
进口javax.mail.MessagingException的;
进口javax.mail.Multipart;
进口javax.mail.PasswordAut​​hentication;
进口javax.mail.Session的;
进口javax.mail.Transport;
进口javax.mail.internet.InternetAddress;
进口javax.mail.internet.MimeBodyPart;
进口的javax.mail.internet.MimeMessage;
进口javax.mail.internet.MimeMultipart;

公共类SendFileEmail
{
 公共无效发送(字符串文件路径)
 {

  //收件人的电子邮件ID需要被提及。
  字符串[email protected];

  //发件人的电子邮件ID需要被提及
  从[email protected]最后的字符串;
 //最后的字符串username =XYZ;
  最终的字符串传递=XYZ123;
  //假设你从本地主机发送电子邮件
  字符串主机=smtp.gmail.com;

  //获取系统属性
  属性属性= System.getProperties();

  //设置邮件服务器
  properties.setProperty(mail.smtp.host,主持人);
  properties.put(mail.smtp.user,从);
  properties.put(mail.smtp.password,通);
  properties.put(mail.smtp.port,587);
  properties.put(mail.smtp.starttls.enable,真);
  properties.put(mail.smtp.auth,真);

  //阅读更多:http://mrbool.com/how-to-work-with-java-mail-api-in-android/27800#ixzz3E2T8ZbpJ


  //获取默认的Session对象。
  //会议会议=作为Session.getDefaultInstance(属性);


  会话会话= Session.getInstance(属性,新javax.mail.Authenticator(){
        受保护的PasswordAut​​hentication的getPasswordAut​​hentication(){
            返回新的PasswordAut​​hentication(从,通);
        }
    });


  尝试{
     //创建一个默认的MimeMessage对象。
     的MimeMessage消息=新的MimeMessage(会议);

     //设置发件人:报头的报头字段。
     message.setFrom(新网际(从));

     //设置为:头部的头字段。
     message.addRecipient(Message.RecipientType.TO,
                              新的网际(0));

     //设置主题:头字段
     message.setSubject(这是主题行!);

     //创建消息部分
     BodyPart的messageBodyPart =新MimeBodyPart();

     //填写消息
     messageBodyPart.setText(这是邮件正文);

     //创建一个multipar消息
     多部分多部分=新MimeMultipart的();

     //设置短信一部分
     multipart.addBodyPart(messageBodyPart);

     //第二部分是附加
     messageBodyPart =新MimeBodyPart();
     数据源源=新FileDataSource(文件路径);
     messageBodyPart.setDataHandler(新的DataHandler(源));
     messageBodyPart.setFileName(文件路径);
     multipart.addBodyPart(messageBodyPart);


     支持MailcapCommandMap MC =(支持MailcapCommandMap)CommandMap.getDefaultCommandMap();
     mc.addMailcap(text / html的;;的X Java的内容处理器= com.sun.mail.handlers.text_html);
     mc.addMailcap(文/ XML ;;的X Java的内容处理器= com.sun.mail.handlers.text_xml);
     mc.addMailcap(text / plain的;;的X Java的内容处理器= com.sun.mail.handlers.text_plain);
     mc.addMailcap(多部分/ * ;;的X Java的内容处理器= com.sun.mail.handlers.multipart_mixed);
     mc.addMailcap(信息/ RFC822 ;;的X Java的内容 - 处理器= com.sun.mail.handlers.message_rfc822);

     //发送完整的消息部分
     message.setContent(多部分);
     // 发信息
     Transport.send(消息);
     的System.out.println(已发送邮件成功......);
  }赶上(MessagingException MEX){
     mex.printStackTrace();
  }
}
 }
 

这样调用方法

 公共类的SendMail {

/ **
 * @参数ARGS
 * /
公共静态无效的主要(字串[] args){
    新SendFileEmail()发送(sample.xlsx);
}

}
 

如果该文件是在资源文件夹例如test.txt的

 文件f =新的文件(getCacheDir()+/ test.txt的);
如果(!f.exists()){尝试

InputStream的是= getAssets()开(的test.txt)。
INT大小= is.​​available();
byte []的缓冲区=新的字节[尺寸]
is.read(缓冲液);
is.close();


FileOutputStream中FOS =新的FileOutputStream(F);
fos.write(缓冲液);
fos.close();
 }赶上(例外五){抛出新的RuntimeException(E); }

新SendFileEmail()发送(f.getPath());
 

I am beginning with android and this is my first program.

This is what my code looks like.I am able to send an email (in background) using this code but unable to attach a file with that as email attachment.I have given permission in mainfest.xml

Please let me know what I am doing wrong and what need to be implemented.

Any help is much appreciated.

import java.net.Authenticator;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import android.annotation.SuppressLint;


public class GMailSender extends javax.mail.Authenticator {
  private String _user;
  private String _pass;

  private String[] _to;
  private String _from;

  private String _port;
  private String _sport;

  private String _host;

  private String _subject;
  private String _body;

  private boolean _auth;

  private boolean _debuggable;

  private Multipart _multipart;


  public GMailSender() {
    _host = "smtp.gmail.com";
    _port = "465";
    _sport = "465";

    _user = "";
    _pass = "";
    _from = "";
    _subject = "";
    _body = "";

    _debuggable = false;
    _auth = true;

    _multipart = new MimeMultipart();

     MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);
  }

  public GMailSender(String user, String pass) {
    this();

    _user = user;
    _pass = pass;
  }

  public boolean send(String to, String from, String subject, String text) {
        return send(new String[] {to}, from, subject, text);
    }
    public boolean send(String[] to, String from, String subject, String text) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", _host);
        props.put("mail.smtp.user", _user);
        props.put("mail.smtp.port", _port);
        props.put("mail.smtp.password", _pass);
        props.put("mail.smtp.socketFactory.port", _port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getInstance(props, this);

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            InternetAddress[] addressTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                addressTo[i] = new InternetAddress(to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addressTo);
            message.setSubject(subject);
            message.setText(text);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    _multipart.addBodyPart(messageBodyPart);
  }

  @Override
  public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(_user, _pass);
  }

  private Properties _setProperties() {
    Properties props = new Properties();
    props.put("mail.smtp.host", _host);
    if(_debuggable) {
      props.put("mail.debug", "true");
    }
    if(_auth) {
      props.put("mail.smtp.auth", "true");
    }
    props.put("mail.smtp.port", _port);
    props.put("mail.smtp.socketFactory.port", _sport);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    return props;
  }
  // the getters and setters
  public String getBody() {
    return _body;
  }
  public void setBody(String _body) {
    this._body = _body;
  }
  // more of the getters and setters …..
}

And how I am calling it in my activity

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;

public class mailActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new PostTask().execute();

        finish();
     }

    public class PostTask extends AsyncTask<String, Void, String>  {
        @Override
        protected String doInBackground(String... params) {
            Log.d("doInBackground","You are in do in background ... ");

            String filepath = "/storage/sdcard0/Bluetooth/2012.jpg";

            Time now = new Time();
            now.setToNow();
            GMailSender sender = new GMailSender("[email protected]","XXX.Password");
            try {
                    sender.addAttachment("/storage/sdcard0/Bluetooth/2012.jpg");
                    sender.send("[email protected]", "[email protected]", "Silent Mail:" + now.format("%d-%m-%Y %H:%M"), "This eMail was sent silently in background");

            catch (Exception e) {
                Log.e("doInBackground","Mail Exception...");
                Log.e("doInBackground", "exception: " + e.toString());
                }
            Log.d("doInBackground", "You completed do in background ... ");
            return null;
        }
    }
}
解决方案
package com.mail.example;

import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendFileEmail
{
 public void send(String filepath)
 {

  // Recipient's email ID needs to be mentioned.
  String to = "[email protected]";

  // Sender's email ID needs to be mentioned
  final String from = "[email protected]";
 // final String username = "xyz";
  final String pass = "xyz123";
  // Assuming you are sending email from localhost
  String host = "smtp.gmail.com";

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.setProperty("mail.smtp.host", host);
  properties.put("mail.smtp.user", from);
  properties.put("mail.smtp.password", pass);
  properties.put("mail.smtp.port", "587");
  properties.put("mail.smtp.starttls.enable","true");
  properties.put("mail.smtp.auth", "true");

  //Read more: http://mrbool.com/how-to-work-with-java-mail-api-in-android/27800#ixzz3E2T8ZbpJ


  // Get the default Session object.
  //Session session = Session.getDefaultInstance(properties);


  Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, pass);
        }
    });


  try{
     // Create a default MimeMessage object.
     MimeMessage message = new MimeMessage(session);

     // Set From: header field of the header.
     message.setFrom(new InternetAddress(from));

     // Set To: header field of the header.
     message.addRecipient(Message.RecipientType.TO,
                              new InternetAddress(to));

     // Set Subject: header field
     message.setSubject("This is the Subject Line!");

     // Create the message part
     BodyPart messageBodyPart = new MimeBodyPart();

     // Fill the message
     messageBodyPart.setText("This is message body");

     // Create a multipar message
     Multipart multipart = new MimeMultipart();

     // Set text message part
     multipart.addBodyPart(messageBodyPart);

     // Part two is attachment
     messageBodyPart = new MimeBodyPart();
     DataSource source = new FileDataSource(filepath);
     messageBodyPart.setDataHandler(new DataHandler(source));
     messageBodyPart.setFileName(filepath);
     multipart.addBodyPart(messageBodyPart);


     MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
     mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
     mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
     mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
     mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
     mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822");

     // Send the complete message parts
     message.setContent(multipart);
     // Send message
     Transport.send(message);
     System.out.println("Sent message successfully....");
  }catch (MessagingException mex) {
     mex.printStackTrace();
  }
}
 }

call the method like this

public class SendMail {

/**
 * @param args
 */
public static void main(String[] args) {
    new SendFileEmail().send("sample.xlsx");
}

}

If the file is in asset folder example test.txt

File f = new File(getCacheDir()+"/test.txt");
if (!f.exists()) try {

InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();


FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
 } catch (Exception e) { throw new RuntimeException(e); }

new SendFileEmail().send(f.getPath());

这篇关于电子邮件使用Java邮件API中的机器人附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 10:50