应用无法发送电子邮件

时间:2018-03-05 13:48:34

标签: android sdk javamail

您好我想从Android模拟器发送电子邮件。目前,即使对于Playstore,模拟器中也没有gmail登录,我正在通过按钮从服务和服务启动asynctask。以下是启动服务的代码段:

Button email = (Button)findViewById(R.id.btn_mail);
        email.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(new Intent(MainActivity.this,EmailService.class));
            }
        });

MyService文件:

package logger.ugi.readlog;


import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by Lenovo on 05/03/2018.
 */

public class EmailService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new EmailAsyncTask().execute();
        if(isOnline()){
      //      new EmailAsyncTask().execute();
        }else{
            Toast.makeText(getApplicationContext(),"Check your Network Connection!",Toast.LENGTH_LONG).show();
        }

        return START_STICKY;
    }

    public boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}

MyAsyncTask文件:

package logger.ugi.readlog;


import android.os.AsyncTask;
import android.os.Environment;


import javax.mail.PasswordAuthentication;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
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 EmailAsyncTask extends AsyncTask<Void,Void,Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        final String username = "sukand@ugi.com";
        final String password = "abcd";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("sukand@ugi.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("abc@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                    + "\n\n No spam to my email, please!");

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            Multipart multipart = new MimeMultipart();

            String file = "";

            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");

            String fileName = "logcat.txt";
            DataSource source = new FileDataSource(dir);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            Transport.send(message);

            System.out.println("Done");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

       return null;
    }
}

问题是它没有发送任何电子邮件,我在日志中获得的是:

03-06 02:22:16.501 4543-4543/logger.ugi.readlog I/dalvikvm: Failed resolving Ljavax/activation/DataHandler; interface 2291 'Ljava/awt/datatransfer/Transferable;'
03-06 02:22:16.501 4543-4543/logger.ugi.readlog W/dalvikvm: Link of class 'Ljavax/activation/DataHandler;' failed
03-06 02:22:16.501 4543-4543/logger.ugi.readlog E/dalvikvm: Could not find class 'javax.activation.DataHandler', referenced from method logger.ugi.readlog.EmailAsyncTask.doInBackground
03-06 02:22:16.501 4543-4543/logger.ugi.readlog W/dalvikvm: VFY: unable to resolve new-instance 2534 (Ljavax/activation/DataHandler;) in Llogger/ugi/readlog/EmailAsyncTask;
03-06 02:22:16.501 4543-4543/logger.ugi.readlog D/dalvikvm: VFY: replacing opcode 0x22 at 0x0096
03-06 02:22:16.501 4543-4543/logger.ugi.readlog I/dalvikvm: Failed resolving Ljavax/activation/DataHandler; interface 2291 'Ljava/awt/datatransfer/Transferable;'
03-06 02:22:16.501 4543-4543/logger.ugi.readlog W/dalvikvm: Link of class 'Ljavax/activation/DataHandler;' failed
03-06 02:22:16.501 4543-4543/logger.ugi.readlog D/dalvikvm: DexOpt: unable to opt direct call 0x4c2c at 0x98 in Llogger/ugi/readlog/EmailAsyncTask;.doInBackground
03-06 02:22:16.505 4543-4599/logger.ugi.readlog D/dalvikvm: GC_FOR_ALLOC freed 328K, 17% free 3017K/3624K, paused 2ms, total 2ms
03-06 02:22:16.513 4543-4599/logger.ugi.readlog D/dalvikvm: GC_FOR_ALLOC freed 302K, 16% free 3071K/3624K, paused 4ms, total 4ms
03-06 02:22:16.521 4543-4599/logger.ugi.readlog D/dalvikvm: GC_FOR_ALLOC freed 306K, 16% free 3072K/3624K, paused 3ms, total 3ms
03-06 02:22:16.525 4543-4599/logger.ugi.readlog D/dalvikvm: GC_FOR_ALLOC freed 309K, 17% free 3017K/3624K, paused 2ms, total 2ms

Gradle文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "logger.ugi.readlog"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile group: 'javax.mail', name: 'mail', version: '1.4.7'
    compile group: 'javax.activation', name: 'activation', version: '1.1'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="logger.ugi.readlog">

    <uses-permission android:name="android.permission.READ_LOGS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".LogService"
            android:enabled="true"
            android:exported="true"/>

        <service android:name=".EmailService"/>
    </application>

</manifest>

请帮我解决这个问题。

编辑:EmailAsyncTask没有启动,所以暂时修复我无法检查互联网是否连接。更改后,AsyncTask启动,现在出现的错误是:

03-06 19:47:15.746 21703-21715/logger.ugi.readlog E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                    Process: logger.ugi.readlog, PID: 21703
                                                                    java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                        at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                                        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                        at java.lang.Thread.run(Thread.java:841)
                                                                     Caused by: java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
                                                                      nested exception is:
                                                                        java.net.ConnectException: failed to connect to smtp.gmail.com/74.125.130.108 (port 25): connect failed: ETIMEDOUT (Connection timed out)
                                                                        at logger.ugi.readlog.EmailAsyncTask.doInBackground(EmailAsyncTask.java:90)
                                                                        at logger.ugi.readlog.EmailAsyncTask.doInBackground(EmailAsyncTask.java:28)
                                                                        at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                            ... 4 more
                                                                     Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
                                                                      nested exception is:
                                                                        java.net.ConnectException: failed to connect to smtp.gmail.com/74.125.130.108 (port 25): connect failed: ETIMEDOUT (Connection timed out)
                                                                        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
                                                                        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
                                                                        at javax.mail.Service.connect(Service.java:310)
                                                                        at javax.mail.Service.connect(Service.java:169)
                                                                        at javax.mail.Service.connect(Service.java:118)
                                                                        at javax.mail.Transport.send0(Transport.java:188)
                                                                        at javax.mail.Transport.send(Transport.java:118)
                                                                        at logger.ugi.readlog.EmailAsyncTask.doInBackground(EmailAsyncTask.java:83)
                                                                            ... 7 more
                                                                     Caused by: java.net.ConnectException: failed to connect to smtp.gmail.com/74.125.130.108 (port 25): connect failed: ETIMEDOUT (Connection timed out)
                                                                        at libcore.io.IoBridge.connect(IoBridge.java:114)
                                                                        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
                                                                        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
                                                                        at java.net.Socket.connect(Socket.java:843)
                                                                        at java.net.Socket.connect(Socket.java:786)
                                                                        at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
                                                                        at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
                                                                        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
                                                                            ... 14 more
                                                                     Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
                                                                        at libcore.io.Posix.connect(Native Method)
                                                                        at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
                                                                        at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
                                                                        at libcore.io.IoBridge.connect(IoBridge.java:112)
                                                                            ... 21 more

我尝试过从587-> 625-> 25更改端口,但没有一个能够解决问题。请帮忙。

2 个答案:

答案 0 :(得分:1)

您正在尝试使用Android中不存在的Java mail api。您需要使用Android-specific library发送电子邮件或自行实施缺少的组件as mentioned here

答案 1 :(得分:1)

使用特殊JavaMail for Android。 (该页面已过期;当前版本为1.6.1。)