用 SendGrid 發送免費電子郵件


1. 概述

SendGrid 免費賬號可以限額發送 100/天封郵件,雖然比 Mailgun 的每月 10000 封的免費額度少,但勝成注冊無需綁定信息卡。

集成 SendGrid 有 SMTP 和 API 兩種方式。官方提供了 Python, Java, GO, Node.js, Ruby, PHP, C# 等語言的 API 庫。

2. 注冊

注冊頁 中會有顯示 reCAPTCHA 驗證,若無顯示,需要KX上網。

3. 集成測試

本文示例使用 Python 3.8 發送郵件。

3.1. 通過 API 庫集成

注冊后在 [api keys](https://app.sendgrid.com/settings/api_keys) 設置頁面創建應用和 API KEY。

官方的 python API 庫是 sendgrid-python, 通過 pip 安裝:

$ pip install sendgrid

測試如下:

import sendgrid
import os
from sendgrid.helpers.mail import *

def send_via_api():
    SENDGRID_API_KEY = "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"
    sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)
    from_email = Email("test@example.com")
    to_email = To("jiang.haiyun@qq.com")
    subject = "Sending with SendGrid is Fun"
    content = Content("text/plain", "and easy to do anywhere, even with Python")
    mail = Mail(from_email, to_email, subject, content)
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)

send_via_api()
202
b''
Server: nginx
Date: Wed, 18 Mar 2020 04:46:11 GMT
Content-Length: 0
Connection: close
X-Message-Id: yrcMLevLRju8p9cEz4cUFg
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html

獲取到的狀態碼 202 表示服務器已接收發送郵件請求。

3.2. 通過 SMTP 集成

注冊后在 SMTP 配置頁 創建 API key,創建后會有 SMTP 相關的配置信息,如:

Server	smtp.sendgrid.net
Ports	25, 587	(for unencrypted/TLS connections) 465	(for SSL connections)
Username	apikey
Password	your_api_key_value

之后可以連接 SMTP 服務器 smtp.sendgrid.net 來發送郵件,其中用戶名為 apikey, 密碼為 your_api_key_value

測試如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def send_via_smpt():
    from_addr = "test@example.com"
    to_addr = "test@example.com"
    password = SENDGRID_API_KEY ="YOUR_API_KEY_VALUE"
    smtp_server = "smtp.sendgrid.net"
    username = "apikey"
    subject = "Sending with SendGrid is Fun"

    msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')

    server = smtplib.SMTP(smtp_server, 587)
    server.set_debuglevel(1)
    server.login(username, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()

send_via_smpt()

資源


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM