当前位置: 代码迷 >> Android >> 我无法通过使用Gmail身份验证的JavaMail API在Android中发送电子邮件,未检测到错误
  详细解决方案

我无法通过使用Gmail身份验证的JavaMail API在Android中发送电子邮件,未检测到错误

热度:93   发布时间:2023-08-04 11:37:48.0

我想要使??用Gmail身份验证的JavaMail API在Android中发送电子邮件,它实际上无法正常工作。甚至没有检测到错误。 我不知道为什么电子邮件没有发送。

这是我自动收到发送电子邮件的链接:

这是主要代码

package com.example.jawa.pos;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileWriter;

import au.com.bytecode.opencsv.CSVWriter;

/**
 * Created by jawa on 10/22/2015.
 */
public class DailyReport_CSV_file extends Activity {
Button csv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
GMailSender sender = new GMailSender("username@gmail.com", "password");
            sender.sendMail("Cold Store", "Daily Report",
                    "user@gmail.com",   
                            "user@yahoo.com");
//            sender.addAttachment("csvcash.csv","Daily Report");
        Toast.makeText(DailyReport_CSV_file.this, "Mail Send Successfully", Toast.LENGTH_SHORT).show();
        finish();
    }
}

这是我的gmailsender.java文件

package com.example.jawa.pos;

/**
 * Created by jawa on 10/23/2015.
 */
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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 java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Provider;
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;
    private Multipart _multipart;

    static {
        Security.addProvider(new com.example.jawa.pos.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");
        _multipart = new MimeMultipart();

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

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }
    public void addAttachment(String filename,String subject) throws MessagingException {
        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(subject);

        _multipart.addBodyPart(messageBodyPart2);
    }


    public synchronized void sendMail(String subject, String body, String sender, String recipients) {
        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);
            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){

        }
    }


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

}

我找不到为什么我的消息没有发送甚至没有发出错误的原因。 谁能给出解决方案?

您是否添加了

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

在你的清单上?

同样,您不能在主线程上进行网络操作。 尝试类似:

private class SendEmail extends AsyncTask<String, Integer, Long> {
    protected Long doInBackground(String... body) {
           try{
        GMailSender sender = new GMailSender("username@gmail.com", "password");
        sender.sendMail("Cold Store", body[0],
                "user@gmail.com",   
                        "user@yahoo.com");
        }catch (Exception e){
            Log.e("Mail Error", e.getMessage());
        }

        return null;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(Long result) {
              Toast.makeText(this, "Mail Send Successfully", Toast.LENGTH_SHORT).show();
    }
}

然后像这样初始化它:

   new SendEmail().execute("Daily Report");
  相关解决方案