使用Mailgun API的简单联系表单

时间:2016-12-19 10:41:13

标签: javascript php jquery email mailgun

我是一名沮丧的前Mandrill用户,突然不得不寻找另一个电子邮件平台。我选择了Mailgun,但我开始后悔这个决定,因为这一切似乎都在我头上。

我能够使用非常基本的javascript / php和Zurb Foundation的验证在我的网站上创建一个简单的联系表单,但我无法确定从哪里开始,只要合并Mailgun的API,我似乎无法找到任何不需要我打开终端或从头开始的文档...

jQuery的:

$('#contact-form').on('valid.fndtn.abide', function() {
    var name = $("input#name").val();
    var email = $("input#email").val();
    var message = $("textarea#message").val();
    //Begin Ajax Call
    $.ajax({
        type: "POST",
        url: "assets/php/mail.php",
        data: {
            'key': 'XXXXXXXX',
            'message': {
                'from_email': email,
                'from_name': name,
                'headers': {
                    'Reply-To': email
                },
                'subject': 'From My Site',
                'text': message,
                'to': [{
                    'email': 'me@me.com',
                    'name': 'me',
                    'type': 'to'
                }]
            }
        },
        success: function() {
            $('#contact-form').html("<div id='success' class='large-6 large-offset-6 medium-12 columns'></div>");
            $('#success').html("<h2 class='collapse'>Message recieved.</h2>")
                .append("<p class='collapse'>Thanks " + name + ", I will be in touch with you shortly.</p>")
                .hide()
                .fadeIn(1500);
        },
    }); //ajax call
    return false;
});

PHP:

<?php

 $name = $_POST['name'];
 $email = $_POST['email'];
 $message = $_POST['message'];

 $msg = "
 Name: $name
 Email: $email
 Commments:
 $message
 ";

 $to = "me@me.com";
 $subject = "From My Site";
 $message = $msg;
 mail($to,$subject,$message,$headers);

 ?>

对于任何有任何Mailgun经验的人,我从哪里开始?我只是希望人们能够从我的网站发送一封电子邮件,而不是必须切换到另一个平台,如SendGrid,并支付10美元/月收到奇怪的电子邮件到处。感谢您的任何见解。

1 个答案:

答案 0 :(得分:0)

    $config = array ();
    $config ['api_key'] = "key-#########################";
    $config ['api_url'] = "https://api.mailgun.net/v3/xyz.com/messages";

    $message = array ();
    $message ['from'] = "SITE NAME < feedback@xyz.com>";
    ;
    $message ['to'] = $to_email;
    $message ['h:Reply-To'] = "SITE NAME < feedback@xyz.com>";
    ;
    $message ['subject'] = 'Test Subject';
    $message ['html'] = '<b>Test Message</b>';
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $config ['api_url'] );
    curl_setopt ( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
    curl_setopt ( $ch, CURLOPT_USERPWD, "api:{$config['api_key']}" );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $message );
    $result = curl_exec ( $ch );
    curl_close ( $ch );
    echo $result;

在使用上述代码之前,您需要创建mailgun帐户&amp;为你的域生成api-key。