[python basic] SMTP send mail

Send Email Tutorial

The syntax is as follows:

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

 

Parameter Description:

host: SMTP server host. You can specify the host's ip address or domain name such as: w3cschool.cc, this is an optional parameter.

port: If you provide the host parameter, you need to specify the port number used by the SMTP service, usually the SMTP port number is 25.

local_hostname: If SMTP is on your local machine, you only need to specify the server address as localhost.

 

The Python SMTP object uses the sendmail method to send mail, the syntax is as follows:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

 

Parameter Description:

from_addr: Email sender address.

to_addrs: String list, email sending addresses.

msg: send message

Pay attention to the third parameter here, msg is a string, which means mail. We know that emails are generally composed of subject, sender, recipient, email content, attachments, etc. When sending emails, pay attention to the format of msg. This format is the format defined in the smtp protocol.

To summarize:

# coding=gbk
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
 
sender = '[email protected]'
receivers = ['[email protected]'] # Receive emails, which can be set to your QQ mailbox or other mailboxes
 
#Common text format
# Three parameters: the first is the text content, the second plain sets the text format, and the third utf-8 sets the encoding
message = MIMEText('Python mail sending test...', 'plain', 'utf-8')
message['From'] = Header("Rookie Tutorial", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP mail test'
message['Subject'] = Header(subject, 'utf-8')

'''
========================================
HTML format mail:
mail_msg = """
    <p>Python mail sending test...</p>
    <p><a href="http://www.runoob.com">This is a link</a></p>
    """
message = MIMEText(mail_msg, 'html', 'utf-8')

message['From'] = Header("Rookie Tutorial", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP mail test'
message['Subject'] = Header(subject, 'utf-8')

=========================================
Emails with attachments:
#Create an instance with attachments
message = MIMEMultipart()
message['From'] = Header("Rookie Tutorial", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP mail test'
message['Subject'] = Header(subject, 'utf-8')
 
#mail body content
message.attach(MIMEText('This is a rookie tutorial Python mail sending test...', 'plain', 'utf-8'))
 
# Construct attachment 1 and transfer the test.txt file in the current directory
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# The filename here can be written arbitrarily, what name is written, what name is displayed in the email
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)
 
# Construct attachment 2 and transfer the runoob.txt file in the current directory
att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
message.attach(att2)

=========================================
Add images to HTML text
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("Rookie Tutorial", 'utf-8')
msgRoot['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP mail test'
msgRoot['Subject'] = Header(subject, 'utf-8')
 
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
  
mail_msg = """
<p>Python mail sending test...</p>
<p><a href="http://www.runoob.com">Rookie Tutorial Link</a></p>
<p>Picture demo:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
 
# Specify the image as the current directory
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
 
# Define image ID, referenced in HTML text
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

=========================================
'''
  
try:
    #local mail server
    smtpObj = smtplib.SMTP('localhost')
    
    '''
    #Third-party mail server method
    mail_host="smtp.XXX.com" #Set up the server
    mail_user="XXXX" #Username
    mail_pass="XXXXXX" #password

    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25) # 25 is the 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")
    
    
    
    

 

A successful example of sending myself through QQ mailbox:

Note that the password is an authorization code, not an email password


 

# coding=gbk
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
 
my_sender='[email protected]' # Sender's email account
my_pass = 'ieovjvjdgtcxbegf' # sender email password
my_user='[email protected]' # The recipient's email account, I will send it to myself here

def mail():
    ret = True
    try:
        #msg=MIMEText('Fill in the email content','plain','utf-8')
        mail_msg = """
            <p>Python mail sending test...</p>
            <p><a href="http://www.runoob.com">This is a link</a></p>
            """
        msg = MIMEText(mail_msg, 'html', 'utf-8')

        msg['From']=formataddr(["FromRunoob",my_sender]) # The corresponding sender's email nickname and sender's email account in brackets
        msg['To']=formataddr(["FK",my_user]) # The corresponding recipient email nickname and recipient email account in brackets
        msg['Subject']="Rookie Tutorial Sending Email Test" # The subject of the email, it can also be said to be the title
 
        # The SMTP server in the sender's mailbox, the port is 25
        #server=smtplib.SMTP("smtp.qq.com", 25)
        
        '''
        QQ mailbox uses the following method to succeed
        '''
        server=smtplib.SMTP_SSL("smtp.qq.com", 465) # The SMTP server in the sender's mailbox, the port is 25
        server.login(my_sender, my_pass) # The sender's email account and email password are in brackets
        server.set_debuglevel(1)
        server.sendmail(my_sender,[my_user,],msg.as_string()) # The corresponding ones in brackets are the sender's email account, the recipient's email account, and the sending email
        server.quit() # close the connection
    except Exception as err: # If the statement in try is not executed, the following ret=False will be executed
        print(err)
        ret = False
    return right
 
ret = mail ()
if ret:
    print("Mail sent successfully")
else:
    print("Failed to send mail")

 。。

 

 

 

 

Guess you like

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