current position:Home>Mail sending, SMTP and exchange sending in Python 3

Mail sending, SMTP and exchange sending in Python 3

2022-02-02 02:45:19 As evidenced by tears

First come SMTP send out

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


def mail():
    """
     adopt smtp
    """

    #  The third party  SMTP  service 
    mail_host = "mail.xxx.com"  #  Setup server 
    mail_user = "xxx.com\xxxx.zhu"  #  user name    Domain account and domain 
    mail_pass = " Mailbox password "  #  password 

    sender = 'xx' # The sender's email account 
    receivers = ['']  #  Receiving mail , Can be set to your QQ Email or other email 

    message = MIMEText('Python  Email send test ...', 'plain', 'utf-8')
    message['From'] = Header(" Novice tutorial ", 'utf-8')
    message['To'] = Header(" test ", 'utf-8')

    subject = 'Python SMTP  Email test '
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 587)  # 25  by  SMTP  Port number 
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print(" Mail sent successfully ")
    except smtplib.SMTPException:
        print("Error:  Unable to send mail ")











Exchange send out 
 Copy code 
# -*- 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,  #  Your email address 
            credentials=Credentials(sendmail, pwd),  #  Email account and password 
            autodiscover=True,
            access_type=DELEGATE
        )

    def mail(self, *args):
        """
         Three parameters need to be passed   Title respectively 、 Content 、 Email address 
        """
        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", ' Your password ', ' Your email account ')
#     Send.mail(" Email title ", ' Email content ', ' Receive email ')
 Copy code 

copyright notice
author[As evidenced by tears],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020245176603.html

Random recommended