python小脚本-发送邮件和微信

一、发送邮件

1、实现发送邮件脚本

如果你对python感兴趣,我这有个学习Python基地,里面有很多学习资料,感兴趣的+Q群:688244617

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()

4、腾讯邮箱实例

import smtplib
from email.mime.text import MIMEText
import string

#第三方SMTP服务
mail_host = "smtp.qq.com"           # 设置服务器
mail_user = "***@qq.com"        # 用户名
mail_pwd  = ""      # 口令,QQ邮箱是输入授权码,在qq邮箱设置 里用验证过的手机发送短信获得,不含空格
mail_to  = ['***@qq.com',]     #接收邮件列表,是list,不是字符串

#邮件内容
msg = MIMEText("傻叉")      # 邮件正文
msg['Subject'] = "大傻叉"     # 邮件标题
msg['From'] = mail_user        # 发件人
msg['To'] = ','.join(mail_to)         # 收件人,必须是一个字符串

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)
    smtpObj.login(mail_user, mail_pwd)
    smtpObj.sendmail(mail_user,mail_to, msg.as_string())
    smtpObj.quit()
    print("邮件发送成功!")
except smtplib.SMTPException:
    print ("邮件发送失败!")

二、发送微信

发送微信必须是微信公众号不能直接给微信发送消息

微信公众平台接口测试帐号申请: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','要发送的内容')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章