1. 从hello world 模板,创建函数“utils_qqmail”
2. 首先这个程序里的模块,都是腾讯云直接支持的,不需要额外安装
index.py 内容,从我的utils项目中,复制过来
# coding:utf-8
"""
发送邮件工具
廖雪峰 SMTP发送邮件
https://www.liaoxuefeng.com/wiki/897692888725344/923057144964288
Python 简单发送邮件 / 发送带各种附件邮件
https://blog.csdn.net/qq_20417499/article/details/80566265
"""
import json
from collections import defaultdict
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import smtplib
import requests
import urllib.parse
import datetime
conf_file = "utils_mail.json" # 配置文件名
class QQMail(object):
""" QQMail 发送邮件 """
def __init__(self, json_conf=None):
# 读取 配置文件, 可以取外部配置
if json_conf is None:
json_conf = conf_file
with open(json_conf) as mail_config:
config = json.load(mail_config)
self.account = config["account"]
self.password = config["password"]
self.smtp_server = config["smtp_server"]
def send_normal(self, to, title, content, mime_type='html'):
"""
发送不带附件的邮件
:param to: list 格式收件人
:param title:
:param content:
:param mime_type: "html" 或 "plain"
:return:
"""
msg = MIMEText(content, _subtype=mime_type, _charset='utf-8')
msg['Subject'] = title
msg['From'] = self.account
msg['To'] = ";".join(to) # 群发邮件要这样设置
server = smtplib.SMTP(self.smtp_server)
server.set_debuglevel(1) # 打印出与服务器交互信息
server.docmd("EHLO server")
server.starttls()
server.login(self.account, self.password) # 登陆
server.sendmail(self.account, to, msg.as_string())
server.close()
def main_handler(event, context):
print("Received event: " + json.dumps(event, indent = 2))
# print("Received context: " + str(context))
try:
server = QQMail()
server.send_normal(
to=event["to"],
title=datetime.datetime.now().strftime("%Y%m%d") + event["title"],
content=event["content"]
)
return("success send")
except Exception as e:
print("error :"+repr(e))
return("error :"+repr(e))
3. 新建1个文件“utils_mail.json”, 这里放邮箱的私密信息
{
"account": "[email protected]",
"smtp_server": "smtp.qq.com",
"password": "xxxx"
}
4. 客服端的测试程序
# coding:utf-8
""" 腾讯云无服务器云函数(Serverless Cloud Function)
1. 云函数-调用方式-公共参数
https://cloud.tencent.com/document/api/583/17238
2. -接口鉴权 v3 申请密钥
https://cloud.tencent.com/document/api/583/33846
申请安全凭证的具体步骤如下:
登录 腾讯云管理中心控制台。
前往 “访问管理->访问密钥->API密钥管理” 的控制台页面。
在 云API密钥 页面,单击【新建密钥】即可以创建一对密钥。
3. python 腾讯云开发者工具套件(SDK)3.0 安装开发包
https://github.com/TencentCloud/tencentcloud-sdk-python
pip install tencentcloud-sdk-python
https://github.com/tencentyun/tencent-serverless-python
pip install tencentserverless
"""
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.scf.v20180416 import scf_client, models
from tencentserverless import scf
from tencentserverless.exception import TencentServerlessSDKException
my_secretId = "xx"
my_secretKey = "yyy"
if __name__ == "__main__":
# 调用 一个云函数
print("prepare to invoke a function!")
try:
postdata = {"to": ["[email protected]"], "title": "it is a test", "content": "测试邮件"} # 入参
data = scf.invoke(function_name='utils_qqmail', secret_id=my_secretId,
secret_key=my_secretKey, region="ap-shanghai", data=postdata)
print(data)
except TencentServerlessSDKException as e:
print(e)
except TencentCloudSDKException as e:
print(e)
except Exception as e:
print(e)
运行日志:
返回数据:
"success send"
日志:
START RequestId: 164b2f2a-2854-11ea-9522-5254007aa7a1
Event RequestId: 164b2f2a-2854-11ea-9522-5254007aa7a1
Received event: {
"content": "\u6d4b\u8bd5\u90ae\u4ef6",
"title": "it is a test",
"to": [
"[email protected]"
]
}
send: 'EHLO server\r\n'
。。。
END RequestId: 164b2f2a-2854-11ea-9522-5254007aa7a1
Report RequestId: 164b2f2a-2854-11ea-9522-5254007aa7a1 Duration:2276ms Memory:128MB MaxMemoryUsed:40.570312MB
调用成功。云函数运行正常。
=================================================
todo:接下去,“云函数”部署到 “API网关”,可以通过api调用方式访问。