Send an email successfully using Python

Python smtolib library

import smtplib
#引入smtplib模块
server = smtplib.SMTP()
#SMTP (Simple Mail Transfer Protocol)翻译过来是“简单邮件传输协议”的意思,
#SMTP 协议是由源服务器到目的地服务器传送邮件的一组规则
server.connect(host, port)#连接(connect)指定的服务器
#我们需要通过SMTP指定一个服务器,这样才能把邮件送到另一个服务器。
server.login(username, password) 
server.sendmail(sender, to_addr, msg.as_string()) 
server.quit() 
  • host is the designated mailbox server to connect to, you can specify the domain name of the server. You can find it by searching for "xx mailbox server address".Insert picture description hereInsert picture description here

  • Port means "port". Port belongs to the content of computer network knowledge, you can search for it yourself, now we only need to know that it is an [integer].

We need to specify the port number used by the SMTP service. Normally, the default port number for SMTP is 25. Network query SMTP settings of NetEase mailbox
Insert picture description here

Get the two parameters of host and port. (Netease mailbox generally closes the SMTP service by default, we have to turn it on first. Remember to write the authorization code)

import smtplib

server = smtp.SMTP()
server.connect('smtp.163.com',465)

Successfully resolved the error smtplib.SMTPServerDisconnected: Connection unexpectedly closed

>>> server.connect('smtp.163.com',465)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/warmtree/anaconda3/lib/python3.7/smtplib.py", line 338, in connect
    (code, msg) = self.getreply()
  File "/home/warmtree/anaconda3/lib/python3.7/smtplib.py", line 394, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Since we are not using the default port 25,

server = smtplib.SMTP_SSL()
#如果端口是用SSL加密,请这样写代码。其中server是变量名
server.connect('smtp.163.com',465,'utf-8')

Successfully resolved the error ValueError: server_hostname cannot be an empty string or start with a leading dot.

here Wallpaper
Python 3.7 modified the ssl.pycause of smtplib.SMTP_SSLthe problem, according to the original wording error.

server=smtplib.SMTP_SSL(host='smtp.gmail.com').connect(host='smtp.gmail.com', port=465)
username = '[email protected]'
password = '你的授权码数字'

server.login(username, password)

The overall module looks like this:

# smtplib 用于邮件的发信动作
import smtplib

# 发信方的信息:发信邮箱,QQ邮箱授权码
from_addr = '[email protected]'
password = '你的授权码数字'

# 收信方邮箱
to_addr = '[email protected]'

# 发信服务器
smtp_server = 'smtp.qq.com'

# 开启发信服务,这里使用的是加密传输
server = smtplib.SMTP_SSL()
server.connect(smtp_server,465)
# 登录发信邮箱
server.login(from_addr, password)
# 发送邮件
server.sendmail(from_addr, to_addr, msg.as_string())
# 关闭服务器
server.quit()

Python email package

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

This is about the difference between "module" and "package". A module (module) is generally a file, and a package (package) is a directory. A package can contain many modules. It can be said that a package is a "module package". "consist of.
But why can I know that email is a package when I see the empty file? This is because all packages in Python must include an init.py file by default.
init.py controls the import behavior of packages. If this file is empty, then we can do nothing if we just import the package. Therefore, importing email directly does not work .
Therefore, we need to use the from… import… statement to import the [needed object] from [a file] in the email package directory. For example, introduce the MIMEText method from the text file in the email package.

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

# MIMEText(msg,type,chartset)
# msg:文本内容,可自定义
# type:文本类型,默认为plain(纯文本)
# chartset:文本编码,中文为“utf-8”
msg = MIMEText('send by python','plain','utf-8')

Insert picture description here

import smtplib
#引入smtplib模块
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
#从email包下的text文件中引入

username='[email protected]'
password=input('please enter the password:')

from_addr = '[email protected]'
to_addr = '[email protected]'

smtp_server='smtp.gmail.com'

# MIMEText(msg,type,chartset)
# msg:文本内容,可自定义
# type:文本类型,默认为plain(纯文本)
# chartset:文本编码,中文为“utf-8”
msg = MIMEText('send by python','plain','utf-8')

'''
server = smtplib.SMTP_SSL(host=smtp_server)
#SMTP (Simple Mail Transfer Protocol)翻译过来是“简单邮件传输协议”的意思,
#SMTP 协议是由源服务器到目的地服务器传送邮件的一组规则
server.connect(host=smtp_server, port=465)#连接(connect)指定的服务器
'''
server = smtplib.SMTP(smtp_server)
server.connect(host=smtp_server, port=25)
#我们需要通过SMTP指定一个服务器,这样才能把邮件送到另一个服务器。
print('连接(connect)指定的服务器')
server.starttls()
server.login(username, password) 
print('finish the password')
server.sendmail(from_addr, to_addr, msg.as_string()) 
print('have sent the emaiL')
#server.sendmail(sender, to_addr, msg.as_string()) 
#from_addr:邮件发送者地址。 
#to_addr:邮件收件人地址。
#msg.as_string():为一个字符串类型 
server.quit() 
print('successfully')

Solve the problem successfully TimeoutError: [Errno 110] Connection timed out

Since NetEase's mailbox is relatively strict, we need to write it all on the list.

import smtplib
#引入smtplib模块
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
#从email包下的text文件中引入
from email.header import Header

username='@163.com'
password=input('please enter the password:')

from_addr = '@163.com'
to_addr = '@163.com'

smtp_server='smtp.gmail.com'

# MIMEText(msg,type,chartset)
# msg:文本内容,可自定义
# type:文本类型,默认为plain(纯文本)
# chartset:文本编码,中文为“utf-8”
msg = MIMEText('send by python','plain','utf-8')
# 邮件头信息
msg['From'] = Header(from_addr)
msg['To'] = Header(to_addr)
msg['Subject'] = Header('python test')

server = smtplib.SMTP_SSL()
#server = smtplib.SMTP_SSL(host=smtp_server)
#SMTP (Simple Mail Transfer Protocol)翻译过来是“简单邮件传输协议”的意思,
#SMTP 协议是由源服务器到目的地服务器传送邮件的一组规则
server.connect(host=smtp_server, port=465)#连接(connect)指定的服务器
'''
server = smtplib.SMTP(smtp_server)
server.connect(host=smtp_server, port=25)
'''
#我们需要通过SMTP指定一个服务器,这样才能把邮件送到另一个服务器。
print('连接(connect)指定的服务器')
server.starttls()
server.login(username, password) 
print('finish the password')
server.sendmail(from_addr, to_addr, msg.as_string()) 
print('have sent the emaiL')
#server.sendmail(sender, to_addr, msg.as_string()) 
#from_addr:邮件发送者地址。 
#to_addr:邮件收件人地址。
#msg.as_string():为一个字符串类型 
server.quit() 
print('successfully')


The reason for the error is because we set the server incorrectly and smtp_server='smtp.gmail.com'changed it tosmtp_server='smtp.163.com'

If you want to send a long content, it is recommended to set a variable text to hold the text content. This is more convenient and trouble-free.

成功解决smtplib.SMTPResponseException: (454, b’Command not permitted when TLS active’)

Delete the code server.starttls()can be

server.starttls() 
#smtplib.SMTPException: No suitable authentication method found

group email

Finally, the template for mass mailing:

import smtplib
# smtplib 用于邮件的发信动作
from email.mime.text import MIMEText
# email 用于构建邮件内容
from email.header import Header
# 用于构建邮件头
import csv
# 引用csv模块,用于读取邮箱信息

# 发信方的信息:发信邮箱,QQ邮箱授权码
# 方便起见,你也可以直接赋值
from_addr = input('请输入登录邮箱:')
password = input('请输入邮箱授权码:')

# 发信服务器
smtp_server = 'smtp.qq.com'

# 邮件内容
text='''我的挚友哦,最近过得怎么样?
		记得常常联系哇!
'''

# 待写入csv文件的收件人数据:人名+邮箱
# 记得替换成你要发送的名字和邮箱
data = [['niannian ', '[email protected]'],['feifei', '[email protected]']]

# 写入收件人数据
with open('to_addrs.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    for row in data:
        writer.writerow(row)

# 读取收件人数据,并启动写信和发信流程
with open('to_addrs.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader: 
        to_addrs=row[1]
        msg = MIMEText(text,'plain','utf-8')
        msg['From'] = Header(from_addr)
        msg['To'] = Header(to_addrs)
        msg['Subject'] = Header('python test')
        server = smtplib.SMTP_SSL()
        server.connect(smtp_server,465)
        server.login(from_addr, password)
        server.sendmail(from_addr, to_addrs, msg.as_string())

# 关闭服务器
server.quit()

Finally, attach the complete code:

import smtplib
#引入smtplib模块
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
#从email包下的text文件中引入
from email.header import Header

username='@163.com'
password=input('please enter the password:')

from_addr = '@163.com'
to_addr = '@163.com'

smtp_server='smtp.163.com'

# MIMEText(msg,type,chartset)
# msg:文本内容,可自定义
# type:文本类型,默认为plain(纯文本)
# chartset:文本编码,中文为“utf-8”
msg = MIMEText('send by python','plain','utf-8')
# 邮件头信息
msg['From'] = Header(from_addr)
#msg['To'] = Header(to_addr)
msg['To'] = Header(','.join(to_addr))
msg['Subject'] = Header('python test')

server = smtplib.SMTP_SSL(smtp_server)
#server = smtplib.SMTP_SSL(host=smtp_server)
#SMTP (Simple Mail Transfer Protocol)翻译过来是“简单邮件传输协议”的意思,
#SMTP 协议是由源服务器到目的地服务器传送邮件的一组规则
server.connect(smtp_server, 465)#连接(connect)指定的服务器
'''
server = smtplib.SMTP(smtp_server)
server.connect(host=smtp_server, port=25)
'''
#我们需要通过SMTP指定一个服务器,这样才能把邮件送到另一个服务器。
print('连接(connect)指定的服务器')
#server.starttls() #smtplib.SMTPException: No suitable authentication method found
server.login(username, password) 
print('finish the password')
server.sendmail(from_addr, to_addr, msg.as_string()) 
print('have sent the emaiL')
#server.sendmail(sender, to_addr, msg.as_string()) 
#from_addr:邮件发送者地址。 
#to_addr:邮件收件人地址。
#msg.as_string():为一个字符串类型 
server.quit() 
print('successfully')


Guess you like

Origin blog.csdn.net/weixin_44991673/article/details/110277298