Idle Works, Idle Thoughts

使用MailGun发送邮件

MailGun提供邮件发送服务。注册完账号后,提供一个域名地址,并配置DNS后,即可使用。

域名配置

MailGun建议使用二级域名,因此我提供了一个inc.berlinix.com的域名专供邮件发送。

1.0 发送邮件的DNS记录

添加一个TXT记录(SPF & DKIM),这样才能用MailGun发送邮件:

TXT inc.berlinix.com v=spf1 include:mailgun.org ~all

2.0 跟踪邮件的DNS记录

CNAME email.inc.berlinix.com mailgun.org

3.0 接受邮件的DNS记录

MX 10 mxa.mailgun.org
MX 10 mxb.mailgun.org

完成配置后,回到MailGun,可以验证域名是否配置成功。

发送邮件

通过curl发送邮件

通过API发送邮件

从Dashboard获取Secret API kye,用于发送邮件。

curl -s --user "api:YOUR-API-KEY" \
    https://api.mailgun.net/v3/inc.berlinix.com/messages \
    -F from="Sales <sales@inc.berlinix.com>" \
    -F to="jack@163.com" \
    -F subject="Hello, sale start" \
    -F text="Testing MailGun send mail."

通过SMTP发送邮件

首先下载一个Perl+Curl写的命令行工具swks:

$ curl http://www.jetmore.org/john/code/swaks/files/swaks-20130209.0/swaks -o swaks
$ chmox + swaks

通过swks发送邮件:

./swaks --auth \
    --server smtp.mailgun.org \
    --au postmaster@inc.berlinix.com \
    --ap PWD-FOR-POSTMASTER \
    --to jack@163.com \
    --h-Subject "Welcome to my shop" \
    --body "Start sales now."

注意,从MailGun的Domains里,找到SMTP发件人邮箱和密码。

通过PHP发送邮件

首先通过composer下载依赖库:

$ cat composer.json 
{
    "require": {
        "phpmailer/phpmailer": "~5.2",
        "mailgun/mailgun-php": "~2.0",
        "php-http/guzzle6-adapter": "^1.0"
    }
}

$ composer install

通过API发送邮件

<?php

require_once("vendor/autoload.php");
use Mailgun\Mailgun;

$client = new Http\Adapter\Guzzle6\Client();
$mailer = new Mailgun("key-", $client);
$domain = "inc.berlinix.com";

$res = $mailer->sendMessage($domain, [
    "from"      => "Sales <sales@inc.berlinix.com>",
    "to"        => "jack@163.com",
    "subject"   => "Say hello",
    "text"      => "Top sale news."
]);

echo $res->http_response_code . "\n";
echo $res->http_response_body->id . "\n";
echo $res->http_response_body->message . "\n";

?>

通过SMTP发送邮件

<?php

require_once("vendor/autoload.php");

$mail = new PHPMailer;

$mail->isSMTP();
$mail->Host = "smtp.mailgun.org";
$mail->SMTPAuth = true;
$mail->Username = "postmaster@inc.berlinix.com";
$mail->Password = "password";
$mail->SMTPSecure = "tls";

$mail->From = "sales@inc.berlinix.com";
$mail->FromName = "Sales";
$mail->addAddress("jack@163.com");  // 收件人邮箱

$mail->Subject = "Say hello";
$mail->Body = "Test for my MailGun.";

if(!$mail->send()) {
    echo "Message cannot be sent.\n";
    echo "Mailer Error: " . $mail->ErrorInfo . "\n";
} else {
    echo "Message has been sent.\n";
}

?>