简体   繁体   中英

want to send Email using JavaMailAPI in android. The code works fine & all info is shown in Log

want to send Email using JavaMailAPI in android. The code works fine & all info is shown in Log. But when I checked my email id nothing sent & nothing has received.

package com.example.android.emailverification;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; 
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements        
View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(this);
}


private void sendEmail() {
    new Thread(new Runnable() {
        public void run() {
            try {
                Log.e(">>", "Inside SendEmail run()");
                GMailSender sender = new GMailSender("*********","*******");
                // sender.addAttachment(mFilePath);
                sender.sendMail("Test mail","This mail has been sent from android app along with attachment", "*******","********");
                Log.v("MainActivity", "Your mail has been sent…");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

@Override
public void onClick(View v) {
    Log.e(">>", "Button clicked");
    sendEmail();
}
}

JSSEProvider.java

import android.util.Log;
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() {
                    Log.e(">>","Inside JSSEPROVIDER");
                    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.java

package com.example.android.emailverification;

import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;   
import javax.mail.Message;
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 GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;

private Multipart _multipart = new MimeMultipart();
static {
    Log.e(">>", "inside multipart");
    Security.addProvider(new JSSEProvider());
}

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

    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");
    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.host", mailhost);

    Log.e(">>", "properties set");
    session = Session.getDefaultInstance(props, this);
    Log.e(">>","Session get");
}

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

/**
 * Use
 * {@link #sendMail(String subject, String body, String sender, String     recipients)}
 *
 */

public synchronized void sendMail(String subject, String body,
                                  String sender, String recipients) throws Exception {
    try {
        Log.e(">>", subject + "\n" + body + "\n" + sender + "\n" + recipients);
        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);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);
        _multipart.addBodyPart(messageBodyPart);

  // Put parts in message
        message.setContent(_multipart);
        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 void addAttachment(String filename) throws Exception {
 /* BodyPart messageBodyPart = new MimeBodyPart();
 DataSource source = new FileDataSource(filename);
 messageBodyPart.setDataHandler(new DataHandler(source));
 messageBodyPart.setFileName(“download Pdf”);

_multipart.addBodyPart(messageBodyPart);*/
/* Message message = new MimeMessage(session);
  Multipart _multipart = new MimeMultipart();  
BodyPart messageBodyPart = new MimeBodyPart();
File sdCard =Environment.getExternalStorageDirectory();
String path=sdCard.getAbsolutePath() + “/pdf/”+”/test.pdf”;
messageBodyPart.setFileName(path);
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);  
_multipart.addBodyPart(messageBodyPart);

  // Put parts in message
  message.setContent(_multipart);*/
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
   _multipart.addBodyPart(messageBodyPart);

    BodyPart messageBodyPart2 = new MimeBodyPart();
    messageBodyPart2.setText("subject43");

    _multipart.addBodyPart(messageBodyPart2);
}

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");
    }
}
}

Logcat

Reconstruct Branch: NOTHING
03-19 22:37:51.817 31943-32009/com.example.android.emailverification      I/OpenGLRenderer: Initialized EGL, version 1.4
03-19 22:37:51.827 31943-32009/com.example.android.emailverification D/OpenGLRenderer: Enabling debug mode 0
03-19 22:37:51.907 31943-31943/com.example.android.emailverification I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1b9c2261 time:1608595
03-19 22:38:05.427 31943-31943/com.example.android.emailverification E/>>: Button clicked
03-19 22:38:05.447 31943-32418/com.example.android.emailverification E/>>: Inside SendEmail run()
03-19 22:38:05.467 31943-32418/com.example.android.emailverification E/>>: inside multipart
03-19 22:38:05.467 31943-32418/com.example.android.emailverification E/>>: Inside JSSEPROVIDER
03-19 22:38:05.507 31943-32418/com.example.android.emailverification E/>>: properties set
03-19 22:38:05.547 31943-32418/com.example.android.emailverification E/>>: Session get
03-19 22:38:05.547 31943-32418/com.example.android.emailverification E/>>:     Test mail
                                                                       This  mail has been sent from android app along with attachment
                                                                       kumesh257@gmail.com
                                                                        yadavumesh8090@gmail.com
03-19 22:38:05.567 31943-31954/com.example.android.emailverification W/art: Suspending all threads took: 6.202ms
03-19 22:38:09.267 31943-32418/com.example.android.emailverification W/System.err: javax.mail.AuthenticationFailedException   
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at javax.mail.Service.connect(Service.java:319)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at javax.mail.Service.connect(Service.java:169)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at javax.mail.Service.connect(Service.java:118)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at javax.mail.Transport.send0(Transport.java:188)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at javax.mail.Transport.send(Transport.java:118)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at   com.example.android.emailverification.GMailSender.sendMail(GMailSender.java:104)    03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at com.example.android.emailverification.MainActivity$1.run(MainActivity.java:28)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification W/System.err:     at java.lang.Thread.run(Thread.java:818)
03-19 22:38:09.277 31943-32418/com.example.android.emailverification V/MainActivity: Your mail has been sent…

检查清单文件中的Internet权限。

There's a lot of unnecessary complexity in your code. First, fix all these common JavaMail mistakes . Then remove your ByteArrayDataSource and use the one that's part of JavaMail , if you need one at all. Which you shouldn't. If you want to set the content of a body part, use the setText method; it's much simpler. And, you're setting the content of the message using a DataHandler, then overwriting the content with a MimeMultipart object, which you added a MimeBodyPart to, but you never set the content of the MimeBodyPart. Basically, you have no idea what you're doing and you've copy and pasted someone else's code without understanding it at all. I suggest copying code from the JavaMail sample programs instead.

Your mail hasn't been sent because you're getting an AuthenticationFailedException. The JavaMail FAQ has Gmail examples . Most likely you need to enable less secure apps .

Also, make sure you're using the official JavaMail for Android .

If that doesn't solve your problem, post the JavaMail debug output .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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