1. 程式人生 > 實用技巧 >034 Django:發訊息示例

034 Django:發訊息示例

一、http://mail.126.com/ 傳送郵件

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

msg = MIMEText('老大,我今天需要請假。', 'plain', 'utf-8')  # 傳送內容
msg['From'] = formataddr(["海燕", '[email protected]'])  # 發件人
msg['To'] = formataddr(["雅玲", '[email protected]'])  # 收件人
msg['Subject'] = "【請回復】請假事宜
" # 主題 server = smtplib.SMTP("smtp.163.com", 25) # SMTP服務 server.login("[email protected]", "密碼") # 郵箱使用者名稱和密碼 server.sendmail('[email protected]', ['[email protected]', ], msg.as_string()) # 傳送者和接收者 server.quit()

二、QQ傳送郵箱

import smtplib
from email.mime.text import MIMEText
_user = "你的qq郵箱"  
_pwd  = "你的授權碼"
_to   
= "[email protected]" msg = MIMEText("Test") #要傳送的內容 msg["Subject"] = "don't panic" #主題 msg["From"] = _user msg["To"] = _to try: s = smtplib.SMTP_SSL("smtp.qq.com ", 465) s.login(_user, _pwd) s.sendmail(_user, _to, msg.as_string()) s.quit() print("Success!") except smtplib.SMTPException as e:
print() print("Falied,%s"%e )
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

class Qq(object):
    '''傳送郵件'''
    def __init__(self):
        self.email = "[email protected]"  #自己的郵箱
        self.user = "不冷不熱的溫柔"  #使用者名稱
        self.pwd = "uwaendbwhypweagi"

    def send(self,subject,body,to,name):
        print(222)
        msg = MIMEText(body, 'plain', 'utf-8')  # 傳送內容
        msg['From'] = formataddr([self.user, self.email])  # 發件人
        msg['To'] = formataddr([name,to])  # 收件人
        msg['Subject'] =subject  # 主題

        server = smtplib.SMTP_SSL("smtp.qq.com", 465) # SMTP服務
        print(333333)
        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": "wx13f235a73fa3b42e",   
            "secret": "7f5a5ccd89f65de2b73e9eb3a4de9bf8",
        }
    ).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('o2Ifb0va8Xp4zIidu8RYAR57ae-U','你好啊')   #別人關注你才能發訊息

四、短息傳送訊息