简体   繁体   English

来自Android的呼叫邮件PHP文件不起作用

[英]Call mail PHP file from Android doesn't work

I have the following function in my Android app: 我的Android应用程序具有以下功能:

void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
        ParseUser currentUser = ParseUser.getCurrentUser();

        StringBuilder messageBuilder = new StringBuilder();
        for (int i=0; i<productsOrdered.size(); i++){
            messageBuilder.append(productsOrdered.get(i)).append("\n");
        }
        String mess = messageBuilder.toString();

        String parameters = "name=" + currentUser.getString(Configurations.USER_FULLNAME) +
                "&fromEmail=" + fromEmail +
                "&receiverEmail=" + receiverEmail +
                "&messageBody=" + mess +
                "&storeName=" + Configurations.MERCHANT_NAME +
                "&shippingAddress=" + currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);

        String strURL = PHPfileUurl + parameters;
        strURL = strURL.replace(" ", "%20");
        strURL = strURL.replace("\n", "%20");

        Log.i(Configurations.TAG, "PHP STRING URL: " + strURL);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            URL url;
            url = new URL(strURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
                InputStream is = conn.getInputStream();
                Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
            } else {
                InputStream err = conn.getErrorStream();
                Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
            }
        } catch (IOException e) {e.printStackTrace(); }
    }

When I call that function the Logcat prints out this message: 当我调用该函数时,Logcat将输出以下消息:

I/log-: PHP STRING URL: http://example.com/myapp/email-admin.php?name=Mark%20Doe&fromEmail=myemail@gmail.com&receiverEmail=admin@mydomain.com&messageBody=PRODUCT%20ID:%20Q3nQgZdlFG%20---%20PRODUCT:%20Nike%20Sport%20Shoes%20black%20%20---%20QUANTITY:%201%20---%20SIZE:%20L%20&storeName=Z%20Store%20Inc.&shippingAddress=John%20Doe,%20121%20Church%20Avenue,%20ASD123,%20London,%20UK
I/log-: EMAIL RESPONSE: OK

So I assume everything is fine since the RESPONSE = OK. 所以我认为一切都很好,因为RESPONSE = OK。 But it's not, because I will not receive any email at admin@mydomain.com (there is another email address, I've posted a fake one just as an example, the Logcat prints out my real email address as receiverEmail ). 但它不是,因为我不会在接受任何admin@mydomain.com电子邮件(还有另外一个电子邮件地址,我已经张贴假的只是作为一个例子,在logcat的打印出我的真实电子邮件地址作为receiverEmail )。

Here's my mail.php file: 这是我的mail.php文件:

// POST Variables
$name = $_POST['name'];
$fromEmail = $_POST['fromEmail'];
$receiverEmail = $_POST['receiverEmail'];
$messageBody = $_POST['messageBody'];
$storeName = $_POST['storeName'];
$shippingAddress = $_POST['shippingAddress'];
$headers = 'From: ' .$fromEmail;

// SUBJECT 
$subject = "New order from " .$name. " on '" .$storeName. "'";


// COMPOSE MESSAGE 
$message = 
"ORDER DETAILS:\n".
$messageBody.
"\n\nName: " .$name. 
"\nUser Email: " .$fromEmail.
"\nShipping Address: " .$shippingAddress
;

/* Finally send email */
mail($receiverEmail,
    $subject, 
    $message, 
    $headers
);

/* Result */
echo "Email Sent to: " .$receiverEmail. "\n Message: " .$message;

Does my code have something wrong? 我的代码有问题吗? is there another way to call a mail.php file from my own server? 还有另一种方法可以从我自己的服务器调用mail.php文件吗? I've also tried this question , but I cannot import the DefaultHttpClient class in my project. 我也尝试过此问题 ,但是无法在项目中导入DefaultHttpClient类。

Use $_GET instead of $_POST , 使用$ _GET代替$ _POST,

change all variable from 更改所有变量

$name = $_POST['name'];

to

$name = $_GET['name'];

it's would be easier if you change the $_POST to $_GET but the problem in the $_GET method if the message have (&something=) inside it you will receive only half the message as the &something= would be set to an other $_GET , Also you might get some problems if the message is too long , 如果将$ _POST更改为$ _GET会更容易,但是如果消息中包含(&something =),则$ _GET方法中的问题将只收到一半消息,因为&something =会设置为其他$ _GET ,如果消息太长,您也可能会遇到一些问题,

so if you want to use the $_POST method instead of the $_GET 因此,如果您想使用$ _POST方法而不是$ _GET

you need to change your java code , make sure to import Map and then change it to this 您需要更改Java代码,请确保导入Map,然后将其更改为

void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
    ParseUser currentUser = ParseUser.getCurrentUser();

    StringBuilder messageBuilder = new StringBuilder();
    for (int i=0; i<productsOrdered.size(); i++){
        messageBuilder.append(productsOrdered.get(i)).append("\n");
    }
    String mess = messageBuilder.toString();


    Map<String,Object> params = new LinkedHashMap<>();
params.put("name", currentUser.getString(Configurations.USER_FULLNAME));
params.put("fromEmail", fromEmail);
params.put("receiverEmail", receiverEmail);
params.put("messageBody", mess);
 params.put("storeName", Configurations.MERCHANT_NAME);
  params.put("shippingAddress", currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);

StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
    if (postData.length() != 0) postData.append('&');
    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
    postData.append('=');
    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");


    String strURL = PHPfileUurl;

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    try {
        URL url;
        url = new URL(strURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(20000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);


        if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
            InputStream is = conn.getInputStream();
            Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
        } else {
            InputStream err = conn.getErrorStream();
            Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
        }
    } catch (IOException e) {e.printStackTrace(); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android上从文本文件读取文件不起作用 - Read File from text file on Android doesn't work 调用站点 #4 bootstrap 方法的异常。 代码在 Android Studio 中不起作用,但在 Eclipse 中有效 - Exception from call site #4 bootstrap method. Code doesn't work in Android studio, but works in Eclipse Qmunicate-Android语音/视频通话无法正常工作 - Qmunicate - Android voice / video call doesn't work correctly 显示邮件发件人不起作用 javamail - Display mail sender doesn't work javamail Java 邮件无法正常工作 - Java mail doesn't work properly 将多个 SSL 证书固定添加到 Android KeyStore 不起作用。 (来自资源文件) - Add multiple SSL certificate pinning to Android KeyStore doesn't work. (from Resource file) 更改从Strings.xml文件读取的文本颜色在android Eclipse的自定义对话框中不起作用 - Change text color that read from Strings.xml file doesn't work in custom Dialog on android Eclipse Android okohttp将数据插入php无法正常工作 - android okohttp insert data into php doesn't work 来自JavaScript的JavaFX WebView up调用不起作用 - JavaFX WebView up call from JavaScript doesn't work 在 Android 10 上使用 action_call 意图拨打电话不起作用 - Make a call using action_call intent on Android 10 doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM