当前位置: 首页 > 知识库问答 >
问题:

无法使用java mail api从android应用程序发送邮件

沈德寿
2023-03-14

我正在尝试使用java mail api从我的android应用程序发送电子邮件,当我在java project中运行代码时,它会成功发送邮件,但当我将此代码用于android应用程序时,logcat显示错误如下:-

09-03 15:18:57.549:ERROR/AndroidRuntime(277):致命异常:main

09-03 15:18:57.549: ERROR/AndreidRuntime(277):java.lang.RuntimeExctive:无法启动活动ComponentInfo{email3.app/email3.app.email3}:java.lang.RuntimeExctive:javax.mail.MessagingExctive:无法连接到SMTP主机:smtp.gmail.com,端口: 465;

09-03 15:18:57.549:ERROR/AndroidRuntime(277):java。网SocketException:权限被拒绝

代码如下:-

文件1:-email3.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

 public class email3 extends Activity {
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    sender s=new sender();

    }
}





file 2 :- sender.java

import java.util.Properties;  
import javax.mail.*;  
import javax.mail.internet.*;  

public class sender {  
 public sender() {  

 String to="xxx@gmail.com";//change accordingly  

  //Get the session object  
  Properties props = new Properties();  
  props.put("mail.smtp.host", "smtp.gmail.com");  
  props.put("mail.smtp.socketFactory.port", "465");  
  props.put("mail.smtp.socketFactory.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("xxx@gmail.com","yyy");//change accordingly  
}  
});  

//compose message  
try {  
MimeMessage message = new MimeMessage(session);  
message.setFrom(new InternetAddress("xxxx@gmail.com"));//change accordingly  
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
message.setSubject("Hello");  
message.setText("Testing.......");  

//send message  
Transport.send(message);  


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

}  
}  




file :- 3  Menifest file

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".email3"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
<uses-permission android:name="android.permission.INTERNET" />
</application>

共有3个答案

艾修然
2023-03-14

步骤1下载邮件、激活、附加jar文件并导入到项目中。下载链接

第2步将这些课程复制并通过你的项目。

GMail。JAVA

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GMail {

    final String emailPort = "587";// gmail's smtp port
    final String smtpAuth = "true";
    final String starttls = "true";
    final String emailHost = "smtp.gmail.com";


    String fromEmail;
    String fromPassword;
    List<String> toEmailList;
    String emailSubject;
    String emailBody;

    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;

    public GMail() {

    }

    public GMail(String fromEmail, String fromPassword,
            List<String> toEmailList, String emailSubject, String emailBody) {
        this.fromEmail = fromEmail;
        this.fromPassword = fromPassword;
        this.toEmailList = toEmailList;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;

        emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", emailPort);
        emailProperties.put("mail.smtp.auth", smtpAuth);
        emailProperties.put("mail.smtp.starttls.enable", starttls);
        Log.i("GMail", "Mail server properties set.");
    }

    public MimeMessage createEmailMessage() throws AddressException,
            MessagingException, UnsupportedEncodingException {

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
        for (String toEmail : toEmailList) {
            Log.i("GMail", "toEmail: " + toEmail);
            emailMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toEmail));
        }

        emailMessage.setSubject(emailSubject);
        emailMessage.setContent(emailBody, "text/html");// for a html email
        // emailMessage.setText(emailBody);// for a text email
        Log.i("GMail", "Email Message created.");
        return emailMessage;
    }

    public void sendEmail() throws AddressException, MessagingException {

        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromEmail, fromPassword);
        Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        Log.i("GMail", "Email sent successfully.");
    }

}

发送邮件任务。JAVA

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import java.util.List;

public class SendMailTask extends AsyncTask {

    private ProgressDialog statusDialog;
    private Activity sendMailActivity;

    public SendMailTask(Activity activity) {
        sendMailActivity = activity;

    }

    protected void onPreExecute() {
        statusDialog = new ProgressDialog(sendMailActivity);
        statusDialog.setMessage("Getting ready...");
        statusDialog.setIndeterminate(false);
        statusDialog.setCancelable(false);
        statusDialog.show();
    }

    @Override
    protected Object doInBackground(Object... args) {
        try {
            Log.i("SendMailTask", "About to instantiate GMail...");
            publishProgress("Processing input....");
            GMail androidEmail = new GMail(args[0].toString(),
                    args[1].toString(), (List) args[2], args[3].toString(),
                    args[4].toString());
            publishProgress("Preparing mail message....");
            androidEmail.createEmailMessage();
            publishProgress("Sending email....");
            androidEmail.sendEmail();
            publishProgress("Email Sent.");
            Log.i("SendMailTask", "Mail Sent.");
        } catch (Exception e) {
            publishProgress(e.getMessage());
            Log.e("SendMailTask", e.getMessage(), e);
        }
        return null;
    }

    @Override
    public void onProgressUpdate(Object... values) {
        statusDialog.setMessage(values[0].toString());

    }

    @Override
    public void onPostExecute(Object result) {
        statusDialog.dismiss();
    }

}

3.现在你可以根据需要更改这个类,也可以使用这个类发送多封邮件。我同时提供xml和java文件。

活动:邮件。xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="30dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="From Email" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:cursorVisible="true"
        android:editable="true"
        android:ems="10"
        android:enabled="true"
        android:inputType="textEmailAddress"
        android:padding="5dp"
        android:textColor="#000000">

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Password (For from email)" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:ems="10"
        android:inputType="textPassword"
        android:padding="5dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="To Email" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:ems="10"
        android:inputType="textEmailAddress"
        android:padding="5dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Subject" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:ems="10"
        android:padding="5dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Body" />

    <EditText
        android:id="@+id/editText5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:ems="10"
        android:inputType="textMultiLine"
        android:padding="35dp"
        android:textColor="#000000" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Email" />

</LinearLayout>

发送邮件活动。JAVA

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Arrays;
import java.util.List;

public class SendMailActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button send = (Button) this.findViewById(R.id.button1);

        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Log.i("SendMailActivity", "Send Button Clicked.");

                String fromEmail = ((TextView) findViewById(R.id.editText1))
                        .getText().toString();
                String fromPassword = ((TextView) findViewById(R.id.editText2))
                        .getText().toString();
                String toEmails = ((TextView) findViewById(R.id.editText3))
                        .getText().toString();
                List<String> toEmailList = Arrays.asList(toEmails
                        .split("\\s*,\\s*"));
                Log.i("SendMailActivity", "To List: " + toEmailList);
                String emailSubject = ((TextView) findViewById(R.id.editText4))
                        .getText().toString();
                String emailBody = ((TextView) findViewById(R.id.editText5))
                        .getText().toString();
                new SendMailTask(SendMailActivity.this).execute(fromEmail,
                        fromPassword, toEmailList, emailSubject, emailBody);
            }
        });
    }
}

注意:别忘了在你的AndroidManifest中添加互联网权限。xml文件

希望它能起作用,如果不是这样的话,请在下面发表评论。

卫高明
2023-03-14

如果使用“smtps”协议通过SSL访问SMTP,则所有属性都将命名为“mail.smtps.*”

使用道具。put(“mail.smtp.port”、“888”) 设置邮件。smtp。端口属性,其类型为int。

戴瑞
2023-03-14

您必须使用asyntask才能使用网络http://mobiledevtuts.com/android/android-sdk-smtp-email-tutorial/

 类似资料:
  • 我研究了以下问题和答案:spring boot-无法连接到SMTP主机:SMTP.gmail.com,端口:25,响应:421 我想做同样的事情--用Gmail服务器从spring boot应用程序发送电子邮件。 我的配置是: 这是从另一个问题复制的,只有用户名和密码已经改变了我的需要。我的scienario唯一不同的是,电子邮件地址的域不是gmail.com。 我的电子邮件客户端类是: 我的例外

  • 我正在用Android开发一个应用程序。我不知道如何从应用程序发送电子邮件?

  • 问题内容: 在我的AngularJS Web应用程序之一中,我需要通过向相关人员发送电子邮件来确认密码。如何在AngularJS中实现呢?我是.NET专家,正在使用Visual Studio 2013。 问题答案: 我已经通过网络服务实现了,请参考下面的代码片段 和ajax调用为

  • 具有以下邮件配置设置: 以及以下属性: 我得到以下错误: JAVAlang.RuntimeException:javax。邮政MessaginException:无法连接到SMTP主机:SMTP。我们德勤。com,端口:25;嵌套的例外是:java。网SocketException:权限被拒绝: 当我使用gmail作为“发件人”帐户和“收件人”中的Outlook帐户时,代码是一样的。 我试着设置s

  • 我有一个IMAP服务器主机名:xyz.com.我的SMTP主机名是:comcast.net. 现在,当我通过Outlook发送电子邮件时,它会自动将我的ID[发件人ID]显示为:myusername@xyz.com而不是myusername@comcast.net. 我想用JavaMail API实现同样的目标。 当我使用JavaMail API时,它将发送者显示为myusername@comca

  • 我使用Android Studio和这个库;https://github.com/yesidlazaro/GmailBackground . 我正在尝试从我的android应用程序发送电子邮件。但是每当我尝试从Gmail帐户发送电子邮件时,它都不起作用。因为谷歌将我的应用程序固定为“不太安全的应用程序”并阻止它。 我不得不从gmail的安全设置中允许不太安全的应用程序。但我不想这样做。我如何解决这