简体   繁体   English

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

[英]Sending mail in android without intents using SMTP

Hi I am developing an android app which will send mail on click of a button.嗨,我正在开发一个 android 应用程序,它将通过单击按钮发送邮件。 Code worked at first but due to some reason its not working now.代码起初工作但由于某种原因它现在不工作。 Could anyone please help me with this?任何人都可以帮我解决这个问题吗? xyz@outlook.com is the recipient. xyz@outlook.com 是收件人。 abc@gmail.com is the sender. abc@gmail.com 是发件人。 I have hard coded the subject and the body of the mail.我对邮件的主题和正文进行了硬编码。

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

Put in your manifest file,放入你的清单文件,

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

check if you have internet connection,检查您是否有互联网连接,

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

and finnaly use this code to send email并最终使用此代码发送电子邮件

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

config gradle as per below define get reference from Here按照下面的配置 gradle 定义从这里获取参考

repositories { 
     jcenter()
     maven {
         url "https://maven.java.net/content/groups/public/"
     }
}

dependencies {
     compile 'com.sun.mail:android-mail:1.5.5'
     compile 'com.sun.mail:android-activation:1.5.5'
}

android {
   packagingOptions {
       pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
   }
}

Add this async task to send mail添加此异步任务以发送邮件

 public class sendemail extends AsyncTask<String, Integer, Integer> {

    ProgressDialog progressDialog;
    private StringBuilder all_email;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(GetuserActivity.this);
        progressDialog.setMessage("Uploading, please wait...");
        progressDialog.show();
        if (selecteduser_arr != null) {
            all_email = new StringBuilder();
            for (int i = 0; i < selecteduser_arr.size(); i++) {
                if (i == 0) {
                    all_email.append(selecteduser_arr.get(i));
                } else {
                    String temp = "," + selecteduser_arr.get(i);
                    all_email.append(temp);
                }
            }
        }
    }

    @Override
    protected Integer doInBackground(String... strings) {

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("enterhereyouremail", "enterherepassword");
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("enterhereyouremail"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("sendermail@gmail.com,sendermail2@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler," +
                    "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

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

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        progressDialog.dismiss();
    }
}

Since you say it worked previously, your app should already be having internet permission and other necessary permissions.既然你说它以前有效,你的应用程序应该已经拥有互联网权限和其他必要的权限。

  1. Check if the current phone you are trying has proper mobile Data /Internet检查您当前使用的手机是否有适当的移动数据/互联网
  2. If connected via wi-fi, check if any new firewall restriction is not allowing the mail to be sent.如果通过 wi-fi 连接,请检查是否有任何新的防火墙限制不允许发送邮件。

Try to use port 465尝试使用 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);
            }
        });
    }

I don't think you have to bombard your android source code with SMTP logic.我认为您不必用 SMTP 逻辑轰炸您的 android 源代码。

Here is what you can do instead :您可以这样做:

  1. Create a web service in php using PHP MAILER使用PHP MAILER在 php 中创建 Web 服务

  2. Use retrofit to call the webservice.使用改造来调用网络服务。

  3. Email sent succesfully!邮件发送成功!

Php mailer is really easy to use and send your emails.Here are some examples: Php 邮件程序非常易于使用和发送电子邮件。以下是一些示例:

Tutorial 1教程一

Tutorial 2教程2

  • The bad news is that you need a web server for doing this!坏消息是您需要一个 Web 服务器来执行此操作!

Here's the code in Kotlin.这是 Kotlin 中的代码。
Make sure to enable less secure app access in Gmail.确保在 Gmail 中启用安全性较低的应用访问。 To use secure access you will need to use OAUTH 2.要使用安全访问,您需要使用 OAUTH 2。
read more at:OAuth 2.0 Mechanism阅读更多内容:OAuth 2.0 机制

    val username = "username"
    val password = "email@gmail.com"
    try {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.host"] = "smtp.gmail.com"
        props["mail.smtp.port"] = "587"

        val session = Session.getInstance(props, object : Authenticator() {
            override fun getPasswordAuthentication(): PasswordAuthentication? {
                return PasswordAuthentication(username, password)
            }
        })

        val message = MimeMessage(session)
        message.setFrom(username)
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("email@gmail.com"))
        message.subject = "Automated Violation Detection Email";
        message.setText(
            "Your Text"
                    
        )

        Thread {
            Transport.send(message)
        }.start()
    } catch (e: Exception) {
        println("Error: $e")
        showToastLong("Oops! Something Went Wrong! Please Try Again")
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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