smtplib module of sending mail by python

Keywords: Python

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

SMTP is simply encapsulated in python, which can send plain text mail, HTML mail and mail with attachments

The syntax for python to create an SMTP object is as follows:

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, which 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: the address of the mail sender.
  • to_addrs: string list, mailing address.
  • msg: send message

Note here that the third parameter, msg, is a string representing a message. We know that email generally consists of title, sender, receiver, email content, attachment, etc. when sending email, we should pay attention to the format of msg. This format is defined in the smtp protocol.

  • Email module: responsible for building email
  • SMTP lib module: responsible for sending mail

Email module: support sending email content as plain text, HTML content, pictures, attachments. There are several types of email modules for different email content forms. They are commonly used as follows:

  • Mime text: (mime media type) the content form is plain text, HTML page (import method: from email. Mime. Text import mime text)
  • Mime image: the content is in the form of a picture (import method: from email.mime.image import MIMEImage)
  • MIMEMultupart: a multi-form combination that can contain text and attachments (import method: from email.mime.multipart import MIMEMultipart)

1. Mime text syntax:

MIMEText(msg,type,chartset)

msg: text content

Type: the text type defaults to plain (plain text)

#When sending HTML format, modify it to HTML, but at the same time, the content of msg is also HTML format.

chartset: text code, "utf-8" in Chinese

#Construct message in TEXT format

  msg = MIMEText("hello.text","plain","utf-8")

  msg["Subject"] = "xxxxx"

  msg["From"] = "xxxx"

  msg["To"] = "xxxx"

#To send the mail content constructed above, use as string to convert the mail content constructed above into string form.

  s.sendmail("xxx","xxx",msg.as_string)

2.MIMEImage, mimemiultipart syntax

msg = MIMEMultipart()

#Instantiate a text object

msg_sub = MIMEText("hello.text","plain","utf-8")

#Add a text message to the MIMEMultipart as the message body.

msg.attach(msg_sub)

 

#Picture as attachment

import os

img_datas = open(os.getcwd()+ "/reports/xxxx.png","rb").read()

msg_img = MIMEImage(img_data)

msg_img.add_header('Content-Disposition','attachment', filename = "xxxx.png" )

msg_img.add_header('Content-ID','<0>')

#Add the picture to mimemiultiplat and send it as an attachment.

msg.attach(mag_img)

~~~~~~~~~~~~~~~~~

Here is the code:

Send text message

# coding=utf-8
import smtplib
from email.mime.text import MIMEText
# Send a message in plain text
msg = MIMEText('hello,send by python_test...','plain','utf-8')
#Email address
sender = 'bmjoker@163.com'
#Email authorization code, non login password
password = 'xxxxxxx'
#Inbox address
#receiver = '19xxxxxxx9@qq.com'
mailto_list = ['19xxxxxxx9@qq.com']   #Group email address

#smtp server 
smtp_server = 'smtp.163.com'
#Email address
msg['From'] = sender
#Inbox address
#msg['To'] = receiver
msg['To'] =';'.join(mailto_list)  #Send multiple email
#theme 
msg['Subject'] = 'hello,i just want to test'

server = smtplib.SMTP(smtp_server,25)  # SMTP protocol default port is 25
server.login(sender,password)          #The ogin() method is used to log in to the SMTP server
server.set_debuglevel(1)               #Print out all information that interacts with the SMTP server.
server.sendmail(sender,mailto_list,msg.as_string()) #msg.as_string() changes the mime text object to str server.quit()

# The first parameter is the sender and the second parameter is the receiver. For example:['hello@163.com','xxx@qq.com',]# The third parameter is what to send
server.quit()

To view all information that interacts with the SMTP server:

Where login() is used to log in to the SMTP server, sendmail() is used to send mail, and if you send mail in groups, you can pass in a recipient mailbox list. The body of the mailbox is str. use as string () to change the MIMEText object into str. password is not the login password of the SMTP server, but the authorization password of the SMTP client:

To send a message with HTML:

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

sender = 'bmjoker@163.com' #Email address
passwd = 'xxxxxxxx' #Sender's email authorization code
receivers = '19xxxxxxx9@qq.com'   #Receiving email

subject = 'python Post mail Html Mail test' #theme

content = "<html><h1>Life is short, I am bmjoker</h1></html>"
msg = MIMEText(content,'html','utf-8')
# msg['Subject'] = subject
msg['Subject'] = Header(subject,'utf-8')
# msg['From'] = sender
msg['From'] = Header('hello','utf-8')
# msg['To'] = receivers
msg['To'] = Header('emmmm','utf-8')
try:
    s = smtplib.SMTP_SSL('smtp.163.com',25)
    s.login(sender,passwd)
    s.sendmail(sender,receivers,msg.as_string())
    print('Send Success')

except:
    print('Send Failure')

emmm.... encountered 554 / 553 problems. If it fails, please refer to smtp for troubleshooting: http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

A common mailbox server (pop3, smtp) address, port:

http://www.cnblogs.com/grefr/p/6089079.html

 

Send mail with pictures:

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

sender = 'bmjoker@163.com'
passwd = 'xxxxxxxx'
receivers = '19xxxxxx9@qq.com'
subject = 'python Mailing belt img Mail test for' #theme

# Create an instance with attachments
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receivers

# Create body
msg.attach(MIMEText('Use python smtplib Modules and email Module auto send mail test','plain','utf-8'))

# Create picture attachment
import os
img_file = open(os.getcwd()+"/a4.jpg",'rb').read()
msg_img = MIMEImage(img_file)
msg_img.add_header('Content-Disposition','attachment', filename = "a4.jpg")
msg_img.add_header('Content-ID', '<0>')
msg.attach(msg_img)

try:
    s = smtplib.SMTP('smtp.163.com',25)
    s.set_debuglevel(1) #Output send mail details
    s.login(sender,passwd)
    s.sendmail(sender,receivers,msg.as_string())
    print('Send Succese')

except:
    print('Send Failure')

Prompt sent successfully, but emmm

Maybe TX was scared by APT attack

 

To send a message with attachments:

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

sender = 'bmjoker@163.com'  #Email address
passwd = 'xxxxxxxxxx'  # Email authorization code
receivers = '19xxxxxx9@qq.com'  #Receiving email

subject = 'python Email test with attachments' #theme
# Create an instance with attachments
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receivers

#Create a body and add a text file to the MIMEMultipart
msg.attach(MIMEText('Use python smtplib Modules and email Module auto send mail test','plain','utf-8'))

#Construct attachment 1 and transfer files under the current directory
att1 = MIMEText(open('testdata.xlsx','rb').read(),'base64','utf-8') # rb read in binary mode
# att1["Content-Type"] = 'application/octet-stream'
# filename is the name of the attachment. You can write whatever name you like and what name is displayed in the email
att1["Content-Disposition"] = 'attachment; filename = "testdata.xlsx" '
#Add attachment to MIMEMultipart
msg.attach(att1)

#Construction attachment 2
att2 = MIMEText(open('db.cfg','rb').read(),'base64','utf-8')
# att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename = "db.cfg" '
#Add attachment to MIMEMultipart
msg.attach(att2)

try:
    s = smtplib.SMTP('smtp.qq.com',25)
    s.set_debuglevel(1) #Output send mail details
    s.login(sender,passwd)
    s.sendmail(sender,receivers,msg.as_string())
    print('Send Succese')

except:
    print('Send Failure')

Posted by marukochan on Sat, 25 Apr 2020 17:02:24 -0700