Python send mail

abstract

1, Introduction

SMTP (Simple Mail Transfer Protocol) is the simple mail transfer protocol. It is a set of rules used to transfer mail from source address to destination address, which controls the transfer mode of mail.

python's smtp lib provides a convenient way to send e-mail. It simply encapsulates the smtp protocol.

Python creates SMTP objects with the following syntax:

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

Parameter Description:

  • host: SMTP server host. You can specify the ip address or domain name of the host, such as runoob.com. This is an optional parameter.
  • Port: if you provide the host parameter, you need to specify the port number used by the SMTP service. Generally, 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: mail sender address.
  • to_addrs: string list, email address.
  • msg: send message

Here, notice the third parameter. msg is a string, which means mail. We know that e-mail is generally composed of title, sender, recipient, e-mail content, attachments, etc. when sending e-mail, we should pay attention to the format of msg. This format is defined in the smtp protocol.

2, Instance

1. A simple example of Python sending mail
#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText

# Third party mail server settings
mail_host = 'smtp.163.com'  # smtp server 
mail_user = '***@163.com'   # Email account to log in
mail_pass = '***'           # Mailbox password or authorization code. smtp needs to be enabled

#Content item, with reference below
senderOne = 'yaokun_130@163.com'     # Sender mailbox (mail_user = ') xx@qq.com ')
receiversOne = ['yaokun_130@163.com','2237553939@qq.com']  # Receiving mailbox, QQ mailbox or other mailboxes can be set
subject = 'Python SMTP Mail sending test'  # Mail subject

message['Subject'] = subject              # theme
message = MIMEText('First email sent', 'plain', 'utf-8')  # content
message['From'] = "{}".format(senderOne)  # sender 
message['To'] = ",".join(receiversOne)    # recipient

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # Enable SSL sending. The port is generally 465
    smtpObj.login(mail_user, mail_pass)         # validate logon
    smtpObj.sendmail(senderOne, receiversOne, message.as_string())  # send out
    print("Mail sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send message")
2. Python sends mail in HTML format
#!/usr/bin/python3

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

# Third party mail server settings
mail_host = 'smtp.163.com'  # smtp server 
mail_user = '***@163.com'   # Email account to log in
mail_pass = '***'           # Mailbox password or authorization code. smtp needs to be enabled

#Content item, with reference below
sender = 'yaokun_130@163.com'  # Sender mailbox (mail_user = ') xx@qq.com ')
receivers = ['yaokun_130@163.com','2237553939@qq.com']  # Receiving mailbox, QQ mailbox or other mailboxes can be set
subject = 'Python SMTP Mail sending test'  #theme
mail_msg = """
<p>Python Mail sending test...</p>
<p><a href="https://Blog. Bwcxtech. Com "> my blog link</a></p>
<p>Picture presentation:</p>
<p><img src="cid:image1"></p>
"""
message = MIMEMultipart('related')
msgAlternative = MIMEMultipart('alternative')

msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
message['Subject'] = Header(subject, 'utf-8')
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message.attach(msgAlternative)

# Specify picture
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Define the picture ID and reference it in HTML text
msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage)

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # Enable SSL sending. The port is generally 465
    smtpObj.login(mail_user, mail_pass)         # validate logon
    smtpObj.sendmail(sender, receivers, message.as_string())  # send out
    print("Mail sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send message")
3. Python sends mail with pictures in HTML format

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

#! / usr / bin / python3import SMTP libfrom email.mime.image import mimeimagefrom email.mime.multipart import mimemultipartfrom email.mime.text import mimetextfrom email.header import header # third party mail server settings mail_host = 'SMTP. 163. Com' # SMTP server mail_user = '***@163.com' # email account to log in mail_pass = '* * *' # email The box password or authorization code needs to open the smtp# content item. Below is the reference sender = 'yaokun_130@163.com '# sender's mailbox (mail_user =') xx@qq.com ')receivers = 'yaokun_ 130@163.com ',' 2237553939@qq.com '# receive mailbox, you can set QQ mailbox or other mailboxes subject =' Python SMTP mail sending test '# subject mail_msg = "" "“ <p>Python mail sending test... < / P > < p > < a href=“ https://blog.bwcxtech.com "> my blog link < / a > < / P > < p > picture demonstration: < / P > < p > < img SRC =" CID: image1 "> < / P >" "" message = mimemultipart ('related ') msgalternative = mimemultipart ('alternative') msgalternative.attach (mimetext (mail_msg, 'HTML', 'UTF-8')) message 'subject' = header (subject, 'UTF-8') Message 'from' = "{}". Format (sender) message 'to' = ",". Join (receivers) message.attach (msgalternative) # specifies the picture FP = open ('test. JPG ','rb') msgimage = mimeimage (FP. Read()) FP. Close() # defines the picture ID, and references msgimage.add_header ('content-id ',' < image1 > ') message.attach (msgimage) try: smtpobj = smtplib.smtp_ssl (mail_host, 465) in HTML text #Enable SSL sending. The port is generally 465 SMTP obj.login (mail_user, mail_pass) # login and verify SMTP obj.sendmail (sender, receivers, message. As_string()) # send print("mail sent successfully") except SMTP lib.smtpexception: print("error: unable to send mail")

4. Python sends mail with attachments

#!/usr/bin/python3

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

# Third party mail server settings
mail_host = 'smtp.163.com'  # smtp server 
mail_user = '***@163.com'   # Email account to log in
mail_pass = '***'           # Mailbox password or authorization code. smtp needs to be enabled

#Content item
sender = 'yaokun_130@163.com'           # Sender mailbox (mail_user = ') xx@qq.com ')
receivers = ['yaokun_130@163.com','2237553939@qq.com']  # Receiving mailbox, QQ mailbox or other mailboxes can be set
subject = 'Python SMTP Mail sending test'     #theme
message = MIMEMultipart()

message.attach(MIMEText('This is Python Mail sending test', 'plain', 'utf-8'))
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message['Subject'] = Header(subject, '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 and 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)

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # Enable SSL sending. The port is generally 465
    smtpObj.login(mail_user, mail_pass)         # validate logon
    smtpObj.sendmail(sender, receivers, message.as_string())    # send out
    print("Mail sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send message")

Posted on Fri, 26 Nov 2021 21:06:04 -0500 by mendoz