簡體   English   中英

如何通過 Mailgun 通過電子郵件發送 Twilio SMS 附件?

[英]How can I email Twilio SMS attachments via Mailgun?

背景:我使用自己的網絡應用程序通過 Twilio 發送和接收 SMS 消息。 我在郵件正文中插入了圖像附件,但希望將其他類型的附件(例如 PDF)發送到我的郵件帳戶。

答案:(見下文。)


Downvoters 的注意事項(他們認為我不應該問和回答我自己的問題:

請花點時間閱讀官方的 StackOverflow 政策(我在寫帖子之前做過)。 截至今天,它讀...

我可以回答我自己的問題嗎?

是的! Stack Exchange 一直明確鼓勵用戶回答他們自己的問題。 如果你有一個你已經知道答案的問題,並且你想公開記錄這些知識,以便其他人(包括你自己)可以稍后找到它,那么在 Stack Exchange 站點上提出和回答你自己的問題是完全可以的.

為了鼓勵人們這樣做,每次您提出問題時,頁面底部都會有一個復選框。 如果您的聲望超過 15 並且已經知道答案,請單擊“提問”頁面底部的“回答您自己的問題”復選框。 輸入您的答案,然后一起提交問題和答案。

有道理吧? 在這種情況下,該帖子提供了有關兩個非常受歡迎的服務(即 Twilio 和 Mailgun)的信息。 如果沮喪的開發人員碰壁了,為什么他們必須提出問題並等待答案而不是輕松找到答案? 99% 的情況下,我無需發布問題即可在 StackExchange 上找到答案。

在瀏覽媒體附件時,我會尋找任何非 .jpg、.gif 或 .png 格式的文件。

    // Look for attachments
    $numMedia = $_REQUEST["NumMedia"];
    if ($numMedia > 0) {
        $attachments = "\n\n";

        // Step through list
        for ($i = 0; $i < $numMedia; $i++) {
            // Get the attachment's URL on Twilio
            $attachment = $_REQUEST["MediaUrl" . $i];

            // If not .jpg, .gif, or .png
            if (!preg_match('~(image/jpeg|image/gif|image/png)~', $_REQUEST["MediaContentType" . $i])) {
                // Inform user in message body
                $attachments .= "[A non-image file was sent.]\n\n";

                // Note the presence of a non-image attachment
                $nonImageAttachment = true;
            }

            // If image, add a link and image tag to the message body
            else {
                $attachments .= "<a href='" . $attachment . "' target='_blank'><img src='" . $attachment . "' target='_blank'></a>\n\n";
            }
        }

        // If there are any non-image attachments, trigger the emailAttachment function
        if ($nonImageAttachment) {
            emailAttachments();
        }
    }

如果找到任何非圖像附件,則觸發emailAttachments函數。 該功能通過電子郵件發送所有附件(甚至圖像),以便將來自單個 SMS 的所有附件保存在一起。

function emailAttachments() {
    // Get global variables for Twilio and Mailgun
    global $twilio_source, $twilio_sid, $twilio_token;
    global $mailTo, $mailFrom, $mailgun_api_key, $mailgun_url, $mailgun_domain;

    // Step through all attachments
    $numMedia = $_REQUEST["NumMedia"];
    if ($numMedia > 0) {
        // Note the recipient's number (in case we need to notify SMS sender of a problem)
        $to = $_REQUEST["To"];

        // Use the sender's number and the time for forming a filename
        $from = $_REQUEST["From"];
        $numericFrom = preg_replace("/[^\d]/", "", $from);
        $timestamp = round(microtime(true));

        // Format the sender's phone number for use in the Subject and Body
        $prefix = substr($from, 1, 1);
        $areaCode = substr($from, 2, 3);
        $exchange = substr($from, 5, 3);
        $line = substr($from, 8);
        $formattedFrom = "{$prefix} ({$areaCode}) {$exchange}-{$line}";

        // Include the attachment count in the Subject (plural if appropriate) 
        $description = $numMedia . " " . ($numMedia == 1 ? "attachment" : "attachments");
        $subject = "Forwarding {$description} from {$formattedFrom}.";

        // Include any SMS Body text in the email's Body
        $body = $_REQUEST["Body"];
        $message = "<p>SMS from {$formattedFrom}</p><p style='margin-left:20px; margin-right:20px; font-family:monospace; color:navy;'>{$body}</p>";

        // Specify the Mailgun parameters (not including the attachments)
        $mailgunParams = array(
            "from" => $mailFrom,
            "to" => $mailTo,
            "subject" => $subject,
            "html" => $message
        );

        // Set a directory and start fetching from Twilio
        $directory = "downloads/";
        for ($i = 0; $i < $numMedia; $i++) {
            // Get the content type that Twilio sent and combine it with the sender's number, the timestamp, file number, and proper extension
            $contentType = $_REQUEST["MediaContentType" . $i];
            $filename = $numericFrom . "." . $timestamp . "." . ($i + 1) . "." . substr($contentType, strrpos($contentType, "/") + 1);

            // Open a file in the download directory
            $file = fopen($directory . $filename, "w+");

            // Fetch the file content with cURL
            $ch = curl_init();
            $options = array(
                CURLOPT_HTTPGET => true,
                CURLOPT_URL => $_REQUEST["MediaUrl" . $i],
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                CURLOPT_USERPWD => "$twilio_sid:$twilio_token",
                CURLOPT_FILE => $file
            );
            curl_setopt_array($ch, $options);
            curl_exec($ch);

            // Close connection
            curl_close($ch);

            // Add the file information to the Mailgun array
            $mailgunParams["attachment[$i]"] = curl_file_create($directory . $filename);
        }  

        // Establish cURL connection to Mailgun
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "api:" . $mailgun_api_key);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_URL, "https://api.mailgun.net/v3/" . $mailgun_domain . "/messages");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $mailgunParams);

        // Parse the result 
        $response = curl_exec($ch);
        $response = strtolower(str_replace("\n", "", trim($response)));
        $result=  json_decode($response, true);
        $status = explode(".", $result["message"]);

        // If the message was not queued, trigger function to notify the sender and post error to log
        if ($status[0] !== "queued") {
            notifySender($from, $to);
            error_log("Message not sent because of " . print_r($status, true));
        }

        // Close connection
        curl_close($ch);

        // Step through the attachment list one more time, and delete the files from the server
        for ($i = 0; $i < $numMedia; $i++) {
            $filename = $numericFrom . "." . $timestamp . "." . ($i + 1) . "." . substr($contentType, strrpos($contentType, "/") + 1);
            unlink($directory . $filename);
        }           
    }
}   

如果 Mailgun 未將郵件排隊,請通知發件人通過電子郵件發送附件。

function notifySender($respondTo, $respondingFrom) {
    // Get parameters for sending through Twilio, as well as a callback URL
    global $twilio_sid, $twilio_token;
    global $website_URL;

    // Get the email address that you want the Sender to use for sending attachments via email instead of SMS
    global $mailToAlternative;

    // Set any parameters you want Twilio to return (e.g., origination time to monitor performance)
    $timestamp = round(microtime(true));
    $callback = $website_URL . "?originated=" . $timestamp;

    // Create Twilio array
    $params = array (
        "From" => $respondingFrom,
        "Body" => "🤖  SERVER AUTO-REPLY:\n\nPlease re-send non-image file(s) to…\n\n{$mailToAlternative}",
        "StatusCallback" => $callback
    );

    // Send to Twilio
    $client = new Client($twilio_sid, $twilio_token);
    $message = $client->messages->create($respondTo, $params);

    // Optionally do something with the result (e.g., write to log file)
    $sid = $message->sid;
    $status = $message->status;
}

暫無
暫無

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

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