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

错误Android:无法连接到SMTP主机:SMTP.gmail.com,端口:465,响应:-1

空成天
2023-03-14

我正在尝试发送电子邮件,但一直收到以下错误:

无法连接到SMTP主机:SMTP.gmail.com,端口:465,响应:-1 javax.mail.MessagingException:无法连接到SMTP主机:SMTP.gmail.com,端口:465,响应:-1在com.sun.mail.SMTP.smtptransport.openserver(smtptransport.java:2088)在com.sun.mail.SMTP.smtptransport.protocolconnect(smtptransport.java:699)在javax.mail.service.connect(smtptransport.java:699)在javax.mail.service.connect(service.java:366)在javax.mail.service.connect(service.java:366)在e.sendmailtask.doinbackground(Sendmailtask.java:40)位于Android.os.AsyncTask$2。Call(asynctask.java:305)位于java.util.concurrent.FutureTask.run(FutureTask.java:237)位于Android.os.AsyncTask$SerialExecutor$1。Run(asynctask.java:243)位于java.util.concurrent.ThreadPoolExecutor.Runworker(ThreadPoolExecutor.1133)位于java.util.concurrent.ThreadPoolExecutor$Worker.Run(ThreadPoolExecutor.607)位于java.lang.Thread.Run(ThreadPoolExecutor.Run)Java:761)

这是我的代码:

package com.tsiw.testeinvite;

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 = "465";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
// final String fromUser = "REMOVED";
// final String fromUserEmailPassword = "REMOVED";

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.html" target="_blank">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.");
}

}

mainactivity.java

package com.tsiw.testeinvite;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button send = (Button) this.findViewById(R.id.enviar);

    send.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            Log.d("SendMailActivity", "Send Button Clicked.");

            final String appPackageName = getPackageName(); // getPackageName()

            //RANDOM PASSWORD
            String output ="";
            char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int j = 0; j < 8; j++) {
                char c = chars[random.nextInt(chars.length)];
                sb.append(c);
            }
            output = sb.toString();

            String fromEmail = "REMOVED";

            String fromPassword = "REMOVED";

            String toEmails = ((TextView) findViewById(R.id.email))
                    .getText().toString();

            List toEmailList = Arrays.asList(toEmails
                    .split(","));

            Log.d("SendMailActivity", "To List: " + toEmailList);

            String emailSubject = "Bem-Vindo à GoGamification";

            String emailBody = ((TextView) findViewById(R.id.texto))
                    .getText().toString();

            String textoB = emailBody +
                    "\n" +"\n"+"\n"+"\n"+
                    "Link para a Google Play Store: " + "\n" + "http://play.google.com/store/apps/details?id=<"+appPackageName+">"+
                    "\n" + "\n"+ "\n"+
                    "Credenciais: "+"\n"+
                    "Password: "+ output;

            new SendMailTask(MainActivity.this).execute(fromEmail, fromPassword, toEmailList, emailSubject, textoB);
        }
    });
} 
}

发送邮件任务

package com.tsiw.testeinvite;

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....");
        Log.d("SendMailTask", "Preparing mail message...");
        androidEmail.createEmailMessage();
        publishProgress("Sending email....");
        Log.d("SendMailTask", "Sending email...");
        androidEmail.sendEmail();
        publishProgress("Email Sent.");
        Log.d("SendMailTask", "Mail Sent.");
    } catch (Exception e) {
        publishProgress(e.getMessage());
        Log.e("SendMailTask", e.getMessage(), e);
        Log.d("SendMailTask", "Não enviou");
    }
    return null;
}

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

}

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

}

共有1个答案

廉宇
2023-03-14

您是否尝试禁用防火墙或防病毒?你能尝试通过不同的端口连接吗?

 类似资料: