簡體   English   中英

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

[英]what i'm doing wrong in 'Volley.newRequestQueue'?

我正試圖通過php從java(android studio)發送一封電子郵件。 因此,我需要在PHP代碼中發布3個參數:“email”,“subject”和“body”。 我認為這是有效的,但我的應用停止在"RequestQueue queue = Volley.newRequestQueue( SendMail.this );"

我用他的構造函數創建了一個名為SendMail的公共類,我試圖像這樣執行:

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

有人能幫助我嗎?

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

我希望使用這種方法發送電子郵件: SendMail( NewPass.this, newwmail,subject , body)但實際輸出不會這樣做。

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

PHP代碼:

<?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}";
} 
?>
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. 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM