douzhi3667 2019-03-29 15:03
浏览 186
已采纳

我在“Volley.newRequestQueue”中做错了什么?

I'm trying to send an email from java (android studio) through php. Thus I need to post 3 parameters: "email", "subject" and "body" in the php code. I think that this is working but my app stop to work in the line "RequestQueue queue = Volley.newRequestQueue( SendMail.this );".

I created a public class called SendMail with his constructor and I tried to execute like this:

SendMail sm = new SendMail( NewPass.this, newwmail, "change password", "your code is: " + RandomCodeSend1 );
//Executing sendmail to send email                                
sm.execute();

Can somebody help me?

public class SendMail extends AppCompatActivity implements View.OnClickListener {

    String Email = null;
    String Subject = null;
    String Body = null;

    //Class Constructor
    SendMail(View.OnClickListener context, String email, String subject, String body) {

        Email = email;
        Subject = subject;
        Body = body;
    }

    @Override
    public void onClick(View v) {

    }

    public void execute() {
        Response.Listener<String> respoListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject( response );

                    boolean success = jsonResponse.getBoolean( "success" );

                    if (success) {
                        Toast.makeText( SendMail.this, "Success", Toast.LENGTH_LONG ).show();
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder( SendMail.this );
                        builder.setMessage( "Error" )
                                .setNegativeButton( "Retry", null )
                                .create().show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        EmailRequest emailRequest = new EmailRequest( Email, Subject, Body, respoListener );
        RequestQueue queue = Volley.newRequestQueue( SendMail.this );
        queue.add( emailRequest );
    }
}

class EmailRequest extends StringRequest {
    private static final String REGISTER_REQUEST_URL="http://172.18.0.206/SendEmail/index.php";
    private Map<String, String> params;
    public EmailRequest(String email, String subject, String body, Response.Listener<String> listener) {
        super(Method.POST, REGISTER_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("email", email);
        params.put("subject", subject);
        params.put("body", body);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
}

I expect to send emails using this method: SendMail( NewPass.this, newwmail,subject , body) but the actual output doesn't do that.

Logcat: at StockManager.SendMail.execute(SendMail.java:94)

PHP code:

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

//Crear una instancia de PHPMailer
$mail = new PHPMailer(true);

try {

//Esto es para activar el modo depuración. En entorno de pruebas lo mejor es 2, en producción siempre 0
// 0 = off (producción)
// 1 = client messages
// 2 = client and server messages
    $mail->SMTPDebug = 2;                                       // Enable verbose debug output

    //Definir que vamos a usar SMTP
    $mail->isSMTP();   

    //Ahora definimos gmail como servidor que aloja nuestro SMTP
    $mail->Host   = 'smtp.gmail.com';           // Specify main and backup SMTP servers

//Tenemos que usar gmail autenticados, así que esto a TRUE
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication

//Definimos la cuenta que vamos a usar. Dirección completa de la misma
    $mail->Username   = "xxxxxxx";               // SMTP username

//Definimos el remitente (dirección y, opcionalmente, nombre)
    $mail->SetFrom('xxxxxxx', 'xxxxxxxxxx');

//Introducimos nuestra contraseña de gmail
    $mail->Password   = "xxxxxxx";                           // SMTP password

//Definmos la seguridad como TLS
    $mail->SMTPSecure = 'tls';                        

//El puerto será el 587 ya que usamos encriptación TLS
    $mail->Port       = 587;                                    // TCP port to connect to

    $email = $_POST['email'];
    //$user = $_POST["---------"];
    $mail->AddAddress($email, 'alfonso');
    $subject = $_POST['subject'];
    $body=$_POST["body"];

    //Esta línea es por si queréis enviar copia a alguien (dirección y, opcionalmente, nombre)
//$mail->AddReplyTo('replyto@correoquesea.com','El de la réplica');

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML

//Definimos el tema del email
    $mail->Subject = $subject;
    $mail->Body    = $body;

    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

//Para enviar un correo formateado en HTML lo cargamos con la siguiente función. Si no, puedes meterle directamente una cadena de texto.
//$mail->MsgHTML(file_get_contents('correomaquetado.html'), dirname(ruta_al_archivo));

//Y por si nos bloquean el contenido HTML (algunos correos lo hacen por seguridad) una versión alternativa en texto plano (también será válida para lectores de pantalla)
//$mail->AltBody = 'This is a plain-text message body';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
} 
?>
  • 写回答

1条回答 默认 最新

  • dongxi3209 2019-04-03 14:30
    关注
    I already solved the problem, in line
    RequestQueue queue = Volley.newRequestQueue( SendMail.java );
    I put SendMail.java instead of Context
    RequestQueue queue = Volley.newRequestQueue( Context );
    and I used the context from the method below: SendMail( View.OnClickListener context, String email, String subject, String body )
    
    Thanks for reading. 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B