【问题标题】:Sending mail in android without intents using SMTP使用 SMTP 在没有意图的情况下在 android 中发送邮件
【发布时间】:2014-09-27 22:48:55
【问题描述】:

您好,我正在开发一个 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;
    }
}
}

【问题讨论】:

  • 您遇到的错误是什么?
  • Grashia 没有收到任何错误,它只是在点击事件时没有发送邮件
  • 检查互联网连接。你换手机了吗?以前它可以在移动设备或模拟器中运行?

标签: android smtp


【解决方案1】:

这是 Kotlin 中的代码。
确保在 Gmail 中启用安全性较低的应用访问。要使用安全访问,您需要使用 OAUTH 2。
阅读更多信息:OAuth 2.0 Mechanism

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

【讨论】:

    【解决方案2】:

    我认为您不必用 SMTP 逻辑轰炸您的 android 源代码。

    你可以这样做:

    1. 使用PHP MAILER在php中创建一个web服务

    2. 使用改造调用网络服务。

    3. 邮件发送成功!

    Php mailer 非常易于使用和发送电子邮件。以下是一些示例:

    Tutorial 1

    Tutorial 2

    • 坏消息是您需要一个 Web 服务器来执行此操作!

    【讨论】:

    • 通过经过身份验证的 SMTP 发送电子邮件非常轻量级。无需不必要地使事情复杂化。
    • @rustyx 我不会说这会使事情复杂化,但我认为这种方式可能对阅读这篇文章的人有用!您还可以在不同的应用程序中重用该 Web 服务!
    【解决方案3】:

    config gradle 如下定义从Here 获取参考

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

    添加此异步任务以发送邮件

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

    【讨论】:

      【解决方案4】:

      尝试使用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);
                  }
              });
          }
      

      【讨论】:

        【解决方案5】:

        放入你的清单文件,

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

        【讨论】:

        • 谢谢 Joao :) 成功了。只是一个简单的问题,我将如何继续添加文件类型的图像作为附件?
        • 如果可以的话你能帮我吗?
        • 只是对像我这样的新手的额外说明 - 此代码需要将 javamail 库和 Net Beans 激活框架添加到项目中
        • 谢谢@duggulous,你的提示真的很有帮助
        • isOnline 中,期待isConnectedOrConnecting 状态真的可取吗?我使用了isConnected,因为无法保证 connecting 状态会完成,或者完成得足够快,以至于在启动 smtp 握手时,连接实际上是可用的。
        【解决方案6】:

        既然你之前说过它可以工作,那么你的应用应该已经拥有互联网权限和其他必要的权限。

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

        【讨论】:

        • 不工作格拉希亚。代码一切正常吗?
        • 您是否更改了代码?你说代码以前可以工作。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 2014-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 2023-03-26
        相关资源
        最近更新 更多