AWS SES通过PHP发送带附件的邮件

AWS发送邮件只能发送不带附件的,可以直接调方法sendEmail,但是发送带附件的邮件,用sendRawEmail必须自己写MIME邮件格式的邮件,不像sendEmail那样方便

参考文档:https://docs.aws.amazon.com/zh_cn/sdk-for-php/v3/developer-guide/welcome.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
require 'aws/aws-autoloader.php';
require 'UserException.php';

use Aws\Credentials\Credentials;
use Aws\Exception\AwsException;
use Aws\Ses\SesClient;

class AwsEmail {
/**
* 发送带附件的邮件
* @param array $toEmailList 目标邮箱组
* @param string $sendContent 邮件正文
* @param string $appName 应用名
* @param string $sender 发送人
* @param string $attachment 附件文件内容
* @param string $attachmentName 附件文件名
* @param string $attachmentType 附件类型
* @return integer
* @throws \Exception
*/
public static function sendRawEmail($toEmailList, $sendContent, $appName, $sender, &$attachment = "", $attachmentName = "", $attachmentType = "Application/xlsx") {
$emailConfig = [
'key' => '替换自己的',
'secret' => '替换自己的',
'region' => 'us-east-1',
'sender' => '默认的发送人',
];
$fromEmail = $sender ?: $emailConfig["sender"];
preg_match('/<title>(.*)<\/title>/', $sendContent, $match);
$subject = $match[1];
$credentials = new Credentials($emailConfig['key'], $emailConfig['secret']);
$SesClient = new SesClient([
'version' => 'latest',
'region' => $emailConfig['region'],
'credentials' => $credentials,
]);
//build the message
if (is_array($toEmailList)) {
$toEmailStr = rtrim(implode(',', $toEmailList), ',');
} else {
$toEmailStr = $toEmailList;
}
$boundary = uniqid("_Part_" . time(), true); //random unique string
$msg =
"To: $toEmailStr\n" .
"From: $fromEmail\n" .
"Subject: $subject\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative;\n" .
" boundary=\"$boundary\"\n" .
"Content-Transfer-Encoding: 8bit\n" .
"\n" .
"This is a multi-part message in MIME format.\n" .
"\n" .
"--$boundary\n" .
"Content-Type: text/plain; charset=utf-8\n" .
"\n" .
strip_tags($sendContent) . "\n" .
"\n" .
"\n" .
"--$boundary\n" .
"Content-Type: text/html; charset=utf-8\n" .
"\n" .
"$sendContent\n" .
"\n" .
"\n" .
"\n" .
"--$boundary";
//add attachments
if (!empty($attachment)) {
$msg .= "\n";
$msg .= "Content-Transfer-Encoding: base64;" . "\n";
$msg .= "Content-Type: $attachmentType; name=$attachmentName;" . "\n";
$msg .= "Content-Disposition: attachment; filename=$attachmentName;" . "\n";
$msg .= base64_encode($attachment);
$msg .= "\n";
$msg .= "--$boundary";
}
//close email
$msg .= "--" . "\n";

//now send the email out
try {
$result = $SesClient->sendRawEmail([
'RawMessage' => [
'Data' => $msg
]
]);
$messageId = $result['MessageId'];
} catch (AwsException $e) {
throw new UserException($e->getMessage());
}
return $messageId;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :