简体   繁体   English

使用android中的java mail api与附件发送电子邮件

[英]eMail with attachment using java mail api in android

I am beginning with android and this is my first program. 我开始使用android,这是我的第一个程序。

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 我已经在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("from.xxx@gmail.com","XXX.Password");
            try {
                    sender.addAttachment("/storage/sdcard0/Bluetooth/2012.jpg");
                    sender.send("to.xxx@gmail.com", "from.xxx@gmail.com", "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 = "abc@gmail.com";

  // Sender's email ID needs to be mentioned
  final String from = "xyz@gmail.com";
 // 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 如果文件位于资产文件夹示例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());

First, clean up your code by getting rid of the socket factory stuff that's not needed . 首先,通过删除不需要的套接字工厂来清理代码。

The reason nothing's being attached is that you're adding a body part to the multipart, but you're never using the multipart. 没有任何附加的原因是你正在为多部分添加一个身体部位,但你从来没有使用过多部分。 You need to set the multipart as the content of your message, and the multipart needs to include body parts for the main text body and the attachment. 您需要将multipart设置为消息的内容,并且multipart需要包含主文本正文和附件的正文部分。 See also the MimeBodyPart.attachFile method. 另请参见MimeBodyPart.attachFile方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM