python3中邮件发送SMTP和Exchange发送

·  阅读 2254

先来SMTP发送

import smtplib
from email.mime.text import MIMEText
from email.header import Header


def mail():
    """
    通过smtp
    """

    # 第三方 SMTP 服务
    mail_host = "mail.xxx.com"  # 设置服务器
    mail_user = "xxx.com\xxxx.zhu"  # 用户名  域账号和域
    mail_pass = "邮箱密码"  # 口令

    sender = 'xx' #发送者的邮箱账号
    receivers = ['']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
    message['From'] = Header("菜鸟教程", 'utf-8')
    message['To'] = Header("测试", 'utf-8')

    subject = 'Python SMTP 邮件测试'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 587)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")











Exchange发送
复制代码
# -*- coding:utf-8 -*-
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody


class Exchange(object):
    def __init__(self, account, pwd, sendmail):
        self.account = account
        self.pwd = pwd
        self.sendmail = sendmail
        self.credentials = Credentials(self.account, self.pwd)
        self.account = Account(
            primary_smtp_address=sendmail,  # 你邮箱地址
            credentials=Credentials(sendmail, pwd),  # 邮箱账号和密码
            autodiscover=True,
            access_type=DELEGATE
        )

    def mail(self, *args):
        """
        需要传三个参数 分别为标题、内容、邮箱地址
        """
        m = Message(
            account=self.account,
            subject=args[0],
            body=HTMLBody(args[1]),
            to_recipients=[Mailbox(email_address=args[2])]
        )
        m.send()


# if __name__ == '__main__':
#     Send = Exchange("xxx.com\xxx.zhu", '你的密码', '你的邮箱账号')
#     Send.mail("邮件标题", '邮件内容', '接收邮箱')
复制代码
分类:
人工智能
标签:
收藏成功!
已添加到「」, 点击更改