本篇導航 發送郵件 發送微信 一、發送郵件 1、實現發送郵件腳本 2、常見SMTP服務 3、封裝對象 二、發送微信 發送微信必須是微信公眾號不能直接給微信發送消息 微信公眾平臺介面測試帳號申請:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?ac ...
本篇導航
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(["姓名", '[email protected]']) # 發件人 發件人郵箱 msg['To'] = formataddr(["習大大", '[email protected]']) # 收件人 收件人郵箱 msg['Subject'] = "【請回覆】主題" # 主題 就是郵件名 server = smtplib.SMTP("smtp.126.com", 25) # SMTP服務 每個種類的郵箱都有特定的SMTP服務 25為固定埠 server.login("[email protected]", "密碼") # 郵箱用戶名和密碼 server.sendmail('[email protected]', ['[email protected]', ], 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','要發送的內容')