Отправка изображения по электронной почте через AJAX - PullRequest
0 голосов
/ 11 февраля 2011

Используя приведенный ниже код, я могу отправить электронное письмо с приложением изображения с другого сервера.

<$php
$to = "your@email.com"; 
$subject = "A test email";
$random_hash = md5(date('r', time()));

$headers = "From: email@example.com\r\nReply-To: email@example.com";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

$attachment = chunk_split(base64_encode(file_get_contents('http://www.ipadwallpapermac.com/wp-content/uploads/2010/06/adriana-lima.jpg')));

$output = "
--PHP-mixed-$random_hash;
Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
--PHP-alt-$random_hash
Content-Type: text/plain; charset='iso-8859-1'
Content-Transfer-Encoding: 7bit

Hello World!
This is the simple text version of the email message.

--PHP-alt-$random_hash
Content-Type: text/html; charset='iso-8859-1'
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is the <b>HTML</b> version of the email message.</p>

--PHP-alt-$random_hash--

--PHP-mixed-$random_hash
Content-Type: application/jpeg; name=testing.jpg
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment
--PHP-mixed-$random_hash--";

mail($to, $subject, $output, $headers);
?>t;

Но, когда я пытаюсь использовать этот код через AJAX (jquery), он отправляет электронное письмо, но без вложения. Что-то мне не хватает?

Вот мой AJAX-скрипт jquery:

$.ajax({
    url: '&lt;?php echo site_url("ajax/email_wallpaper/".$post_details->id); ?&gt;',
    type: 'POST',
    dataType: 'json',
    data: $.param({'email':$('#email_address').val()}),
    crossDomain: true, 
    complete: function(data) {
        //called when complete
    },
    success: function(data) {
        console.log(data);
        if(data.status == 'success'){
            setTimeout(function(){
                $('#basic-modal-content .status')
                .addClass('no_bg')
                .find('p')
                .html('Success! The wallpaper has been sent to your email.');
                setTimeout('$.modal.close();', 1000);
            }, 1000);
        }
    },
    error: function(data) {
        $('#basic-modal-content .status')
        .addClass('no_bg')
        .find('p')
        .html('Please provide a valid email address.');
        console.log(data);
        console.log(data.responseText);
        //called when there is an error
    }
});

1 Ответ

0 голосов
/ 24 февраля 2011

что это? Вы не упомянули эту функцию site_url () выше ...

$.ajax({
url: '&lt;?php echo site_url("ajax/email_wallpaper/".$post_details->id); ?&gt;',

То, что вы хотите попробовать, это не писать php в вашем javascript.

Первый бит PHP, который вы разместили, должен быть помещен в файл PHP, чтобы вы могли вызвать этот файл в параметре.

Код не обязательно должен быть в этом файле. Конечно, вы можете просто вызвать функцию php, но вы должны включить файл функций в файл, который вызовет ajax.

так что вместо приведенного выше кода ваш параметр URL ajax будет выглядеть так:

$.ajax({
url: '/email-with-attatchment.php',
type: 'POST',
dataType: 'json',
data: $.param({'email':$('#email_address').val()}),
crossDomain: true, 
complete: function(data) {
    //called when complete
},
success: function(data) {
    console.log(data);
    if(data.status == 'success'){
        setTimeout(function(){
            $('#basic-modal-content .status')
            .addClass('no_bg')
            .find('p')
            .html('Success! The wallpaper has been sent to your email.');
            setTimeout('$.modal.close();', 1000);
        }, 1000);
    }
},
error: function(data) {
    $('#basic-modal-content .status')
    .addClass('no_bg')
    .find('p')
    .html('Please provide a valid email address.');
    console.log(data);
    console.log(data.responseText);
    //called when there is an error
}

});

Попробуйте сделать это, затем попытайтесь снова понять, в чем проблема ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...