你如何在Android中使用JavaMail API发送邮件? [英] How do you send mail in Android using JavaMail API?

查看:170
本文介绍了你如何在Android中使用JavaMail API发送邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Android电子发送邮件?同样的code是一个Java项目,但不是在Android的正常工作。

1)GmailSender.java

 进口的javax.activati​​on.DataHandler;
       进口javax.activati​​on.DataSource;
       进口javax.mail.Message;
       进口javax.mail.PasswordAut​​hentication;
       进口javax.mail.Session的;
       进口javax.mail.Transport;
       进口javax.mail.internet.InternetAddress;
       进口的javax.mail.internet.MimeMessage;
       进口java.io.ByteArrayInputStream中;
       进口java.io.IOException异常;
       进口的java.io.InputStream;
       进口java.io.OutputStream中;
       进口java.security.Security;
       进口java.util.Properties;       公共类GMailSender扩展javax.mail.Authenticator {
       私人字符串邮件主机=smtp.gmail.com;
       私人字符串用户;
       私人字符串密码;
       私人会话的会话;       静态的 {
       Security.addProvider(新com.idocz.JSSEProvider());
       }       公共GMailSender(用户字符串,字符串密码){
       this.user =用户;
       this.password =密码;       属性道具=新特性();
       props.setProperty(mail.transport.protocol,SMTP);
       props.setProperty(mail.host,邮件主机);
       props.put(mail.smtp.auth,真);
       props.put(mail.smtp.port,465);
       props.put(mail.smtp.socketFactory.port,465);
       props.put(mail.smtp.socketFactory.class
       javax.net.ssl​​.SSLSocketFactory);
       props.put(mail.smtp.socketFactory.fallback,假);
       props.setProperty(mail.smtp.quitwait,假);       会议=作为Session.getDefaultInstance(道具,这一点);
       }       受保护的PasswordAut​​hentication的getPasswordAut​​hentication(){
       返回新的PasswordAut​​hentication(用户名,密码);
       }       公共同步无效的sendmail(字符串主题,绳体,字符串发件人,收件人字符串)抛出异常{
       的MimeMessage消息=新的MimeMessage(会话);
       DataHandler的处理程序=新的DataHandler(新ByteArrayDataSource(body.getBytes(),text / plain的));
       message.setSender(新网际地址(发件人));
       message.setSubject(一级学科);
       message.setDataHandler(处理);
       如果(recipients.indexOf(,)大于0)
       message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(收件人));
       其他
       message.setRecipient(Message.RecipientType.TO,新的网际地址(收件人));
       Transport.send(消息);
       }       公共类ByteArrayDataSource实现的DataSource {
       私人字节[]数据;
       私人字符串类型;       公共ByteArrayDataSource(字节[]数据,字符串类型){
       超();
       this.data =数据;
       this.type =类型;
       }       公共ByteArrayDataSource(字节[]数据){
       超();
       this.data =数据;
       }       公共无效的setType(字符串类型){
       this.type =类型;
       }       公共字符串的getContentType(){
       如果(类型== NULL)
       返回应用程序/八位字节流;
       其他
       返回类型;
       }       公众的InputStream的getInputStream()抛出IOException
       返回新ByteArrayInputStream的(数据);
       }       公共字符串的getName(){
       返回ByteArrayDataSource
       }       公众的OutputStream的getOutputStream()抛出IOException
       抛出新IOException异常(不支持);
       }
       }
       }

2)JSSEProvider.java

 进口java.security.AccessController;
        进口java.security.Provider中;        公共final类JSSEProvider扩展提供商{
    私有静态最后的serialVersionUID长1L =;
    公共JSSEProvider(){
     超(HarmonyJSSE1.0,和谐JSSE提供者);
     在AccessController.doPrivileged(新java.security.PrivilegedAction<无效>(){
         公共无效的run(){
                把(SSLContext.TLS
                        org.apache.harmony.xnet.provider.jsse.SSLContextImpl);
                放(Alg.Alias​​.SSLContext.TLSv1,TLS);
                把(KeyManagerFactory.X509
                        org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl);
                把(TrustManagerFactory.X509
                        org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl);
                返回null;
            }
        });
    }
}     GMailSender发件人=新GMailSender(xxx@gmail.com,XXXXXX);
     sender.sendMail(测试,测试邮件,xxx@gmail.com,xxx@gmail.com);

GMailSender级呼叫在活动课,但我得到了错误。

  05-07 19:59:42.729:E / dalvikvm(9567):找不到类的com.test.GMailSender,从法引用com.test.sendmail $ 2的onClick     05-07 19:59:43.739:E / AndroidRuntime(9567):致命异常:主要    05-07 19:59:43.739:E / AndroidRuntime(9567):java.lang.NoClassDefFoundError的:com.test.GMailSender


解决方案

首先,你必须为添加3瓶 *的的库文件的文件夹的*这是低于


  1. 的activati​​on.jar

  2. additionnal.jar

  3. 的mail.jar

添加此code在你的应用程序之后。

其次,你必须在允许添加的的Andr​​oidManifest.xml 文件

 <使用许可权的android:NAME =android.permission.INTERNET对/>

MainActivity.java

 包com.example.mailsenderactivity;进口android.os.Bundle;
进口android.app.Activity;
进口android.util.Log;
进口android.view.Menu;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.Toast;公共类MainActivity延伸活动{@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    最终按钮发送=(按钮)this.findViewById(R.id.send);
    send.setOnClickListener(新OnClickListener(){        公共无效的onClick(视图v){
            尝试{
                GMailSender发件人=新GMailSender(&​​LT;üřGMAIL地址>,
                        < Gmail密码>);
                sender.sendMail(这是主题,这是身体,
                        <üřGMAIL(发送器)>中,<收件人(接收器)EMAIL地址>);
                Toast.makeText(MainActivity.this,邮件发送成功.....,Toast.LENGTH_LONG).show();
            }赶上(例外五){
                Log.e(的SendMail,e.getMessage(),E);
            }        }
    });
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}}

GMailSender.java

 包com.example.mailsenderactivity;进口的javax.activati​​on.DataHandler;
进口javax.activati​​on.DataSource;
进口javax.mail.Message;
进口javax.mail.PasswordAut​​hentication;
进口javax.mail.Session的;
进口javax.mail.Transport;
进口javax.mail.internet.InternetAddress;
进口的javax.mail.internet.MimeMessage;
进口java.io.ByteArrayInputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口java.security.Security;
进口java.util.Properties;公共类GMailSender扩展javax.mail.Authenticator {
 私人字符串邮件主机=smtp.gmail.com;
 私人字符串用户;
 私人字符串密码;
 私人会话的会话;静态的 {
    Security.addProvider(新JSSEProvider());
}公共GMailSender(用户字符串,字符串密码){
    this.user =用户;
    this.password =密码;    属性道具=新特性();
    props.setProperty(mail.transport.protocol,SMTP);
    props.setProperty(mail.host,邮件主机);
    props.put(mail.smtp.auth,真);
    props.put(mail.smtp.port,465);
    props.put(mail.smtp.socketFactory.port,465);
    props.put(mail.smtp.socketFactory.class
            javax.net.ssl​​.SSLSocketFactory);
    props.put(mail.smtp.socketFactory.fallback,假);
    props.setProperty(mail.smtp.quitwait,假);    会议=作为Session.getDefaultInstance(道具,这一点);
}受保护的PasswordAut​​hentication的getPasswordAut​​hentication(){
    返回新的PasswordAut​​hentication(用户名,密码);
}公共同步无效的sendmail(字符串主题,绳体,字符串发件人,收件人字符串)抛出异常{
    尝试{
    的MimeMessage消息=新的MimeMessage(会话);
    DataHandler的处理程序=新的DataHandler(新ByteArrayDataSource(body.getBytes(),text / plain的));
    message.setSender(新网际地址(发件人));
    message.setSubject(一级学科);
    message.setDataHandler(处理);
    如果(recipients.indexOf(,)大于0)
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(收件人));
    其他
        message.setRecipient(Message.RecipientType.TO,新的网际地址(收件人));
    Transport.send(消息);
    }赶上(例外五){
        e.printStackTrace();
    }
}公共类ByteArrayDataSource实现的DataSource {
    私人字节[]数据;
    私人字符串类型;    公共ByteArrayDataSource(字节[]数据,字符串类型){
        超();
        this.data =数据;
        this.type =类型;
    }    公共ByteArrayDataSource(字节[]数据){
        超();
        this.data =数据;
    }    公共无效的setType(字符串类型){
        this.type =类型;
    }    公共字符串的getContentType(){
        如果(类型== NULL)
            返回应用程序/八位字节流;
        其他
            返回类型;
    }    公众的InputStream的getInputStream()抛出IOException
        返回新ByteArrayInputStream的(数据);
    }    公共字符串的getName(){
        返回ByteArrayDataSource
    }    公众的OutputStream的getOutputStream()抛出IOException
        抛出新IOException异常(不支持);
    }
  }
}

JSSEProvider.java

 包com.example.mailsenderactivity;进口java.security.AccessController;
进口java.security.Provider中;公共类JSSEProvider扩展提供商{/ **
 *
 * /
私有静态最后的serialVersionUID长1L =;公共JSSEProvider(){
    超(HarmonyJSSE1.0,和谐JSSE提供者);
    在AccessController.doPrivileged(新java.security.PrivilegedAction<无效>(){
        公共无效的run(){
            把(SSLContext.TLS
                    org.apache.harmony.xnet.provider.jsse.SSLContextImpl);
            放(Alg.Alias​​.SSLContext.TLSv1,TLS);
            把(KeyManagerFactory.X509
                    org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl);
            把(TrustManagerFactory.X509
                    org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl);
            返回null;
        }
    });
  }
}

How do you send mail from Android? The same code is working fine in a Java project but not in Android.

1) GmailSender.java

       import javax.activation.DataHandler;
       import javax.activation.DataSource;
       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;
       import java.io.ByteArrayInputStream;
       import java.io.IOException;
       import java.io.InputStream;
       import java.io.OutputStream;
       import java.security.Security;
       import java.util.Properties;

       public class GMailSender extends javax.mail.Authenticator {
       private String mailhost ="smtp.gmail.com";
       private String user;
       private String password;
       private Session session;

       static {
       Security.addProvider(new com.idocz.JSSEProvider());
       }

       public GMailSender(String user, String password) {
       this.user = user;
       this.password = password;

       Properties props = new Properties();
       props.setProperty("mail.transport.protocol", "smtp");
       props.setProperty("mail.host", mailhost);
       props.put("mail.smtp.auth", "true");
       props.put("mail.smtp.port","465");
       props.put("mail.smtp.socketFactory.port", "465");
       props.put("mail.smtp.socketFactory.class",
       "javax.net.ssl.SSLSocketFactory");
       props.put("mail.smtp.socketFactory.fallback", "false");
       props.setProperty("mail.smtp.quitwait", "false");

       session = Session.getDefaultInstance(props, this);
       }

       protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication(user, password);
       }

       public synchronized void sendMail(String subject, String body, String sender,                                  String recipients) throws Exception {
       MimeMessage message = new MimeMessage(session);
       DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(),            "text/plain"));
       message.setSender(new InternetAddress(sender));
       message.setSubject(subject);
       message.setDataHandler(handler);
       if (recipients.indexOf(',') > 0)
       message.setRecipients(Message.RecipientType.TO,            InternetAddress.parse(recipients));
       else
       message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
       Transport.send(message);
       }

       public class ByteArrayDataSource implements DataSource {
       private byte[] data;
       private String type;

       public ByteArrayDataSource(byte[] data, String type) {
       super();
       this.data = data;
       this.type = type;
       }

       public ByteArrayDataSource(byte[] data) {
       super();
       this.data = data;
       }

       public void setType(String type) {
       this.type = type;
       }

       public String getContentType() {
       if (type == null)
       return "application/octet-stream";
       else
       return type;
       }

       public InputStream getInputStream() throws IOException {
       return new ByteArrayInputStream(data);
       }

       public String getName() {
       return "ByteArrayDataSource";
       }

       public OutputStream getOutputStream() throws IOException {
       throw new IOException("Not Supported");
       }
       }
       }

2) JSSEProvider.java

        import java.security.AccessController;
        import java.security.Provider;

        public final class JSSEProvider extends Provider {
    private static final long serialVersionUID = 1L;
    public JSSEProvider() {
     super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
     AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
         public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}

     GMailSender sender = new GMailSender("xxx@gmail.com", "xxxxxx");
     sender.sendMail("Test", "Test mail",  "xxx@gmail.com", "xxx@gmail.com");     

GMailSender class call in activity class but I got error.

     05-07 19:59:42.729: E/dalvikvm(9567): Could not find class 'com.test.GMailSender', referenced from method com.test.sendmail$2.onClick

     05-07 19:59:43.739: E/AndroidRuntime(9567): FATAL EXCEPTION: main

    05-07 19:59:43.739: E/AndroidRuntime(9567): java.lang.NoClassDefFoundError: com.test.GMailSender

解决方案

Firstly you have to add 3 jar *files in libs folder* which are below

  1. activation.jar
  2. additionnal.jar
  3. mail.jar

After add this code in your application.

Secondly you have to add permission in AndroidManifest.xml file

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

MainActivity.java

package com.example.mailsenderactivity;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            try {
                GMailSender sender = new GMailSender("<U R GMAIL ADDRESS>",
                        "<GMAIL PASSWORD>");
                sender.sendMail("This is Subject", "This is Body",
                        "<U R GMAIL (SENDER)>", "<RECIPIENT(RECEIVER) EMAIL ADDRESS>");
                Toast.makeText(MainActivity.this, "Mail Send Successfully.....", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Log.e("SendMail", e.getMessage(), e);
            }

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

GMailSender.java

package com.example.mailsenderactivity;

import javax.activation.DataHandler;   
import javax.activation.DataSource;   
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;   
import java.io.ByteArrayInputStream;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.OutputStream;   
import java.security.Security;   
import java.util.Properties; 

public class GMailSender extends javax.mail.Authenticator {   
 private String mailhost = "smtp.gmail.com";   
 private String user;   
 private String password;   
 private Session session;   

static {   
    Security.addProvider(new JSSEProvider());   
}  

public GMailSender(String user, String password) {   
    this.user = user;   
    this.password = password;   

    Properties props = new Properties();   
    props.setProperty("mail.transport.protocol", "smtp");   
    props.setProperty("mail.host", mailhost);   
    props.put("mail.smtp.auth", "true");   
    props.put("mail.smtp.port", "465");   
    props.put("mail.smtp.socketFactory.port", "465");   
    props.put("mail.smtp.socketFactory.class",   
            "javax.net.ssl.SSLSocketFactory");   
    props.put("mail.smtp.socketFactory.fallback", "false");   
    props.setProperty("mail.smtp.quitwait", "false");   

    session = Session.getDefaultInstance(props, this);   
}   

protected PasswordAuthentication getPasswordAuthentication() {   
    return new PasswordAuthentication(user, password);   
}   

public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
    try{
    MimeMessage message = new MimeMessage(session);   
    DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
    message.setSender(new InternetAddress(sender));   
    message.setSubject(subject);   
    message.setDataHandler(handler);   
    if (recipients.indexOf(',') > 0)   
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
    else  
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
    Transport.send(message);   
    }catch(Exception e){
        e.printStackTrace();
    }
}   

public class ByteArrayDataSource implements DataSource {   
    private byte[] data;   
    private String type;   

    public ByteArrayDataSource(byte[] data, String type) {   
        super();   
        this.data = data;   
        this.type = type;   
    }   

    public ByteArrayDataSource(byte[] data) {   
        super();   
        this.data = data;   
    }   

    public void setType(String type) {   
        this.type = type;   
    }   

    public String getContentType() {   
        if (type == null)   
            return "application/octet-stream";   
        else  
            return type;   
    }   

    public InputStream getInputStream() throws IOException {   
        return new ByteArrayInputStream(data);   
    }   

    public String getName() {   
        return "ByteArrayDataSource";   
    }   

    public OutputStream getOutputStream() throws IOException {   
        throw new IOException("Not Supported");   
    }   
  }   
}  

JSSEProvider.java

package com.example.mailsenderactivity;

import java.security.AccessController;
import java.security.Provider;

public class JSSEProvider extends Provider {

/**
 * 
 */
private static final long serialVersionUID = 1L;

public JSSEProvider() {
    super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
    AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
        public Void run() {
            put("SSLContext.TLS",
                    "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
            put("Alg.Alias.SSLContext.TLSv1", "TLS");
            put("KeyManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
            put("TrustManagerFactory.X509",
                    "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
            return null;
        }
    });
  }
}

这篇关于你如何在Android中使用JavaMail API发送邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆