python如何实现电子邮件的发送

注明:邮箱如果发送失败,则会报错,可以使用异常处理来检测邮件是否会发送失败

常用SMTP地址

1、QQ邮箱(mail.qq.com)

POP3服务器地址:pop.qq.com(端口:110)

SMTP服务器地址:smtp.qq.com(端口:25)

2、搜狐邮箱(sohu.com):

POP3服务器地址:pop3.sohu.com(端口:110)

SMTP服务器地址:smtp.sohu.com(端口:25)

3、HotMail邮箱(hotmail.com):

POP3服务器地址:pop.live.com(端口:995)

SMTP服务器地址:smtp.live.com(端口:587)

4、移动139邮箱:

POP3服务器地址:POP.139.com(端口:110)

SMTP服务器地址:SMTP.139.com(端口:25)

5、景安网络邮箱:

POP3服务器地址:POP.zzidc.com(端口:110)

SMTP服务器地址:SMTP.zzidc.com(端口:25)

本博客转自https://www.jianshu.com/p/29ced38b5183?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=qq

电子邮件
python发送电子邮件时,使用标准库中的smtplib和email,smptlib中有一个SMTP类,需要发送邮件时,初始化该类返回smtpserver对象,使用login登陆MUA,使用sendmail方法发送邮件,邮件的正文用email.mime.text.MIMEText对象进行描述
简单电子邮件发送程序

from email.mime.text import MIMEText
msg = MIMEText('hello message','plain', 'utf-8')
from_addr = '[email protected]'
to_addr = '[email protected]'
sub_msg = 'hello'
smtp_server = 'smtp.163.com'
import smtplib
# 初始化smtp对象,传入服务器地址与端口号
server = smtplib.SMTP(smtp_server,25)
# 设置调试模式可以让我们看到发送邮件过程中的信息
server.set_debuglevel(1)
# 登陆MUA,使用账户与授权码登陆
server.login(from_addr, 'yourpassword')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'important message'
server.sendmail(from_addr, [to_addr], msg.as_string())

邮件被放入垃圾邮件中,如下

发送带附件的电子邮件

 from email.mime.text import MIMEText
 from smtplib import SMTP
 from email.mime.multipart import MIMEMultipart
 
 
 from_addr = '[email protected]'
 to_addr = '[email protected]'
 smtp_server = 'smtp.163.com'
 smtp_port = 25
 subject_msg = 'subject'

 mul_msg = MIMEMultipart()
 mul_msg['From'] = from_addr
 mul_msg['To'] = to_addr
 mul_msg['Subject'] = subject_msg

 msg = MIMEText('\n\rimportant message\n\r', 'plain', 'utf-8')
 mul_msg.attach(msg)

 att1 = MIMEText(open('program.txt','rb').read(), 'base64', 'utf-8')
 att1['Content-Type'] = 'application/octet-stream'
 att1["Content-Disposition"] = 'attachment;filename="program.txt"'
 mul_msg.attach(att1)

 smtp = SMTP(smtp_server, smtp_port)
 smtp.login(from_addr, 'youpass')
 smtp.set_debuglevel(1)
 smtp.sendmail(from_addr, to_addr, mul_msg.as_string())
 smtp.close()

使用第三方开源库yagmail发送电子邮件

import yagmail
yag = yagmail.SMTP(user='[email protected]', password='you pass', host='smtp.qq.com', port=25)
contents = ['import message','program.txt']
yag.send(to='dest', subject='subject', contents=contents)

使用pop3协议用网易邮箱发送邮件时,容易被网易识别为垃圾邮件,可以使用qq邮箱
 

猜你喜欢

转载自blog.csdn.net/qq_16069927/article/details/82291270