问题 使用SMTP在没有意图的情况下在android中发送邮件


嗨,我正在开发一个Android应用程序,将点击一个按钮发送邮件。代码起初工作,但由于某种原因它现在不起作用。有人可以帮我这个吗? xyz@outlook.com是收件人。 abc@gmail.com是发件人。  我已经对主题和邮件正文进行了硬编码。

package com.example.clc_construction;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import android.app.Activity;
import android.app.ProgressDialog;  
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;


public class Email extends Activity
{
public String jobNo;
public String teamNo;
private static final String username = "abc@gmail.com";
private static final String password = "000000";
private static final String emailid = "xyz@outlook.com";
private static final String subject = "Photo";
private static final String message = "Hello";
private Multipart multipart = new MimeMultipart();
private MimeBodyPart messageBodyPart = new MimeBodyPart();
public File mediaFile;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_screen);
    Intent intent = getIntent();
    jobNo = intent.getStringExtra("Job_No");
    teamNo = intent.getStringExtra("Team_No"); 
    sendMail(emailid,subject,message);

}
private void sendMail(String email, String subject, String messageBody)
 {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        }
        catch (AddressException e)
        {
            e.printStackTrace();
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
    }


private Session createSessionObject()
{
    Properties properties = new Properties();
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");

    return Session.getInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    });
}

private Message createMessage(String email, String subject, String messageBody, Session session) throws 

MessagingException, UnsupportedEncodingException
{
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("xzy@outlook.com", "Naveed Qureshi"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
    message.setSubject(subject);
    message.setText(messageBody);
    return message;
}



public class SendMailTask extends AsyncTask<Message, Void, Void>
{
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(Email.this, "Please wait", "Sending mail", true, false);
    }

    @Override
    protected void onPostExecute(Void aVoid)
    {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
    }

    protected Void doInBackground(javax.mail.Message... messages)
    {
        try
        {
            Transport.send(messages[0]);
        } catch (MessagingException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
}

3999
2017-08-05 10:00


起源

你得到的错误是什么? - Nishanthi Grashia
Grashia没有收到任何错误,只是邮件没有在点击事件上发送 - Naveed
检查互联网连接。你换过手机了吗?以前它在移动或模拟器中工作? - Nishanthi Grashia


答案:


放入你的清单文件,

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

检查你是否有互联网连接,

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

并最终使用此代码发送电子邮件

final String username = "username@gmail.com";
final String 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");

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("from-email@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("to-email@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();

        messageBodyPart = new MimeBodyPart();
        String file = "path of file to be attached";
        String fileName = "attachmentName"
        DataSource source = new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Done");

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

12
2017-08-05 10:19



谢谢Joao :)它有效。只是一个简单的问题,我将如何继续添加一个类型为file的图像作为附件? - Naveed
我更改代码以使用附加 - João Marcos
如果可能的话,你能帮助我吗? - Naveed
对于像我这样的新手来说,这只是一个额外的注释 - 这段代码需要将javamail库和Net Beans Activation Framework添加到项目中 - duggulous
谢谢@duggulous,你的暗示真的很有帮助 - Milad Metias


既然您说它以前有效,那么您的应用应该已经拥有互联网权限和其他必要的权限。

  1. 检查您正在尝试的当前手机是否具有正确的移动数据/互联网
  2. 如果通过Wi-Fi连接,请检查是否有任何新的防火墙限制不允许发送邮件。

0
2017-08-05 10:07



没有工作Grashia。代码一切正常吗? - Naveed
你有没改变代码?你说代码以前工作过。 - Nishanthi Grashia


尝试使用端口465

 private Session createSessionObject()
    {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.smtp.host", "smtp.gmail.com");
        properties.setProperty("mail.smtp.port", "465");

        return Session.getInstance(properties, new javax.mail.Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(username, password);
            }
        });
    }

0
2017-08-05 10:11



没有工作Ludger - Naveed
你得到的错误是什么? - Ludger