本篇导航
1、实现发送邮件脚本
import smtplib from email.mime.text import MIMEText from email.utils import formataddr msg = MIMEText(‘邮件内容‘, ‘plain‘, ‘utf-8‘) # 发送内容 发送格式plain就是文本格式 utf-8编码格式 msg[‘From‘] = formataddr(["姓名", ‘xxxx@126.com‘]) # 发件人 发件人邮箱 msg[‘To‘] = formataddr(["习大大", ‘ooooo@qq.com‘]) # 收件人 收件人邮箱 msg[‘Subject‘] = "【请回复】主题" # 主题 就是邮件名 server = smtplib.SMTP("smtp.126.com", 25) # SMTP服务 每个种类的邮箱都有特定的SMTP服务 25为固定端口 server.login("xxxx@126.com", "密码") # 邮箱用户名和密码 server.sendmail(‘xxxx@126.com‘, [‘ooooo@qq.com‘, ], msg.as_string()) # 发送者和接收者 server.quit()
2、常见SMTP服务
@foxmail.com--->smtp.foxmail.com @163.com--->smtp.163.com @k65.net--->www.k65.net @operamail.com--->smtpx.operamail.com
3、封装对象
import smtplib from email.mime.text import MIMEText from email.utils import formataddr class Email(object): def __init__(self): self.email = "***@126.com" self.user = "发件人" self.pwd = ‘密码‘ def send(self,subject,body,to,name): msg = MIMEText(body, ‘plain‘, ‘utf-8‘) # 发送内容 msg[‘From‘] = formataddr([self.user,self.email]) # 发件人 msg[‘To‘] = formataddr([name, to]) # 收件人 msg[‘Subject‘] = subject # 主题 server = smtplib.SMTP("smtp.126.com", 25) # SMTP服务 server.login(self.email, self.pwd) # 邮箱用户名和密码 server.sendmail(self.email, [to, ], msg.as_string()) # 发送者和接收者 server.quit()
发送微信必须是微信公众号不能直接给微信发送消息
微信公众平台接口测试帐号申请:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
# pip3 install requests import requests import json def get_access_token(): """ 获取微信全局接口的凭证(默认有效期俩个小时) 如果不每天请求次数过多, 通过设置缓存即可 """ result = requests.get( url="https://api.weixin.qq.com/cgi-bin/token", params={ "grant_type": "client_credential", "appid": "wx89085e915d351cae", "secret": "64f87abfc664f1d4f11d0ac98b24c42d", } ).json() if result.get("access_token"): access_token = result.get(‘access_token‘) else: access_token = None return access_token def sendmsg(openid,msg): access_token = get_access_token() body = { "touser": openid, "msgtype": "text", "text": { "content": msg } } response = requests.post( url="https://api.weixin.qq.com/cgi-bin/message/custom/send", params={ ‘access_token‘: access_token }, data=bytes(json.dumps(body, ensure_ascii=False), encoding=‘utf-8‘) ) # 这里可根据回执code进行判定是否发送成功(也可以根据code根据错误信息) result = response.json() print(result) if __name__ == ‘__main__‘: sendmsg(‘oK7y70g8OUdJWat84Nkt4sCnN5vg‘,‘要发送的内容‘)