刘明野

python smtp发送邮件

SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib和email两个模块
以下是常用邮箱SMTP端口及登录说明

邮箱SMTP服务器登录口令支持加密方式对应端口号
163smtp.163.com个人设置授权码明文/SSL加密25/465
126smtp.126.com个人设置授权码明文/SSL加密25/465
QQsmtp.qq.com系统分配授权码明文/SSL加密/TLS加密25/465/587
Gmailsmtp.gmail.com邮箱登录密码TLS加密587

mail.py 文件

import smtplib
from email.mime.text import MIMEText

class Email():
    def __init__(self, mail_user, mail_password, smtp_sever, smtp_port):
        self.server = smtplib.SMTP_SSL(smtp_sever, smtp_port)
        self.server.ehlo()
        self.server.login(mail_user, mail_password)

    def sendmail(self, _from, _to, subject, content):
        if type(_to) == str:
            _to = [_to]
        msg = MIMEText(content, 'plain', 'utf-8')
        msg["Subject"] = subject
        msg["From"] = _from
        msg["To"] = ", ".join(_to)
        self.server.sendmail(_from, _to, msg.as_string())

    def close(self):
        self.server.close()

使用方法

from mail import Email
Email = Email('账号','密码','smtp.163.com',465)
Email.sendmail('发件人','收件人','主题','内容')
Email.close()
本文为作者刘明野发布,未经允许禁止转载!
2980
0
0
发表留言

友情链接