aslamhus / sendgrid-email-wrapper
SendGrid API v3的流畅接口,提供构建和发送电子邮件的方法,包括动态模板数据、附件以及各种内容类型等功能
Requires
- sendgrid/sendgrid: ^8.1
Requires (Dev)
- phpunit/phpunit: ^9.6
- vlucas/phpdotenv: ^5.6
README
概览
这个PHP库,Aslamhus/Email
,是一个方便灵活的包装器,用于与SendGrid API v3.0.0交互。它旨在提供发送电子邮件的流畅接口,使将电子邮件功能集成到您的PHP项目中变得简单。该类包括编写和发送电子邮件的方法,包括动态模板数据、附件等特性。
安装/设置
要在项目中使用此类,请按照以下步骤操作:
-
在Sendgrid上创建一个账户。
-
在新sendgrid账户中创建一个API密钥。在仪表板侧边栏中选择
EmailApi
,然后从下拉菜单中选择集成指南
。选择WebApi -> Php,然后创建您的API密钥。您不需要通过composer安装sendgrid,安装此类将为您完成此操作。集成指南的最后一步是发送验证电子邮件。在我们这样做之前,请安装库。 -
创建一个单独的发送者身份。这将允许您从认证的电子邮件地址发送电子邮件。在侧边栏中选择
发送者认证
,然后选择验证单个发送者
。按照步骤操作。您将在发送电子邮件时使用此电子邮件在from
方法中。 -
安装
Aslamhus/Email
composer require aslamhus/sendgrid-email-wrapper
-
发送验证电子邮件(可选)
// add your api key $email = new Email('your-sendgrid-api-key'); // make sure to add your single sender identity email and name $didSend = $email->sendVerifyIntegrationEmail(['verified@example.com', 'Verified User']); // $didSend will return true if everything is set up correctly.
-
确认验证。返回您的Sendgrid账户中的集成指南,然后在页面底部选择
验证集成
。您应该会收到一条确认信息,表明您的集成成功。
用法
发送基本电子邮件
$email = new Email('your-sendgrid-api-key') ->setFrom('sender@example.com', 'Sender Name') ->addTo('recipient@example.com', 'Recipient Name') ->setSubject('Test email') ->addContent('text/plain', 'Hello world!') ->send();
发送包含动态模板数据的电子邮件
动态模板数据变量可以使用handlebars
{{my_var}}设置。更多信息请参阅https://docs.sendgrid.com/for-developers/sending-email/using-handlebars
$email = new Email('your-sendgrid-api-key') ->setFrom('sender@example.com', 'Sender Name') ->addTo('recipient@example.com', 'Recipient Name') ->setSubject('Test email') ->setTemplateId('your-template-id') ->addDynamicTemplateDatas([ 'subject' => 'My dynamic template email' 'name' => '2020-01-01', 'link' => 'https://www.example.com', ]) ->send();
其他特性
-
添加附件
$email->addAttachment('path/to/file.pdf', 'application/pdf', 'document.pdf');
-
添加内容
$email->addContent('text/plain', 'This is the plain text content'); $email->addContent('text/html', '<p>This is the HTML content</p>');
-
获取电子邮件响应
// retrieve the response body, headers and status code after sending $response = $email->getResponse(); print_r($response->headers()); echo $response->statusCode() echo $response->body()
资源
问题和贡献
如果您遇到任何问题或想为此类的发展做出贡献,请访问GitHub存储库:Aslamhus\Email。
测试
要在此库上运行测试,请按照以下步骤操作:
- 设置sample.env文件中的所需字段,然后将sample.env重命名为.env
- 运行测试
composer run test
许可协议
此类是开源的,并按照MIT许可协议发布。请随意使用、修改和分发,以满足您项目的需求。