Python study notes - send email

1. First, you need to register a NetEase mailbox, open the smtp service, and use its authorization code

2. Python script to send email

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

# 3rd party SMTP service  
mail_host = "smtp.163.com" # SMTP server
mail_user = "XXX" # username
mail_pass = "XXX" # Authorization password, not login password

sender = "[email protected]" # Sender's mailbox (preferably write all, otherwise it will fail)
receivers = ["[email protected]"] # Receive emails, which can be set to your QQ mailbox or other mailboxes

content = 'I use Python'
title = 'Life is too short' # Email subject  


def sendEmail ():
    message = MIMEText(content, 'plain', 'utf-8') # content, format, encoding
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465) # Enable SSL sending, the port is generally 465  
        smtpObj.login(mail_user, mail_pass) # Login verification  
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送  
        print("mail has been send successfully.")
    except smtplib.SMTPException as e:
        print (s)


def send_email2(SMTP_host, from_account, from_passwd, to_account, subject, content):
    email_client = smtplib.SMTP(SMTP_host)
    email_client.login(from_account, from_passwd)
    # create msg  
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')  # subject  
    msg['From'] = from_account
    msg['To'] = to_account
    email_client.sendmail(from_account, to_account, msg.as_string())

    email_client.quit()


if __name__ == '__main__':
    sendEmail ()
    # receiver = '***'  
    # send_email2(mail_host, mail_user, mail_pass, receiver, title, content)  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325150267&siteId=291194637