hand
_1_5_47
4
返回栏目
1k
9k
1k
1k
5k
1k
1k
1k
1k
3k
2k
1k
0.8k
2k
3k
1k
1k
0.7k
0.9k
1k
0.6k
0.4k
0.4k
0.3k
3k
2k
9k
0.4k
0.4k
0.8k
0.5k
3k
5k
1k
2k
2k
3k
5k
1k
1k
0.4k
0.5k
0.4k
0.6k
0.7k
1k
0.4k
0.3k
4k
0.5k
0k
0.3k
0k
0.2k
0.2k
0.3k
0.9k
0.9k
0.1k
0.9k
0.9k
1k
0.5k
6k
0.3k
0.4k
0.7k
0.6k
8k
3k
1k
1k
1k
1k
0k
2k
1k
1k
0.2k
5k
4k
5k
0.4k
0.8k
1k
1k
1k
0.1k
2k
1k
2k
6k
0k
2k
7k
1k
5k
2k
3k
1k
0k
1k
0.9k
0.4k
0.2k
1k
3k
4k
1k
1k
1k
2k
3k
0.7k
0.3k
0.5k
0.6k
1k
0.9k
3k
0.3k
4k
返回python栏目
作者:
贺及楼
成为作者
更新日期:2024-10-27 18:05:48
Python 的 smtplib
库用于发送电子邮件。它提供了SMTP(简单邮件传输协议)客户端会话的实现,支持邮件的发送、附件的添加以及与SMTP服务器的交互。smtplib
允许程序自动发送邮件通知、处理邮件列表、实现邮件功能集成等,是自动化邮件处理和通信任务的重要工具。
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText # 引入mail.mime的MIMEText 类来实现支持HTML格式的邮件(email.mime是smtplib模块邮件内容主体的扩展)
class send_email_class():
def __init__(self, msg_from, passwd, server, port):
self.msg_from = msg_from
self.passwd = passwd
self.server = server
self.port = port
def emailpost(self, msg_to, subject, content):
msg = content
msg['Subject'] = subject
msg['From'] = self.msg_from
msg['To'] = msg_to
print(msg)
try:
s = smtplib.SMTP_SSL(self.server, self.port) # 邮件服务器及端口号
s.login(self.msg_from, self.passwd)
s.sendmail(self.msg_from, msg_to, msg.as_string())
print ("发送成功")
except:
print ("发送失败")
finally:
s.quit()
def send_html(self, msg_to, subject, content):
content_html = MIMEText(content)
self.emailpost(msg_to, subject, content_html)
def send_txt_file(self, msg_to, subject, file_name):
data = ""
with open(file_name, 'r') as f:
list1 = f.readlines()
for i in range(0, len(list1)):
list1[i] = list1[i].replace('\n','\r\n') # 普通分行换到邮件分行
data = data+list1[i]
self.emailpost(msg_to, subject, data)
def send_text(self, msg_to, subject, content):
self.emailpost(msg_to, subject, content)
if __name__ == "__main__":
msg_from='XXXXXXXX@qq.com' # 发送方邮箱
passwd='XXXXXXXXXXX' # 填入发送方邮箱的授权码,授权码 - 去邮箱后台开启
server = "smtp.qq.com" # 邮件服务器
port = 465 # port端口号
send_email = send_email_class(msg_from, passwd, server, port)
msg_to='XXXXXXXX@qq.com' # 收件人邮箱
subject="python邮件测试" # 主题
content_html = "<p style='color:#ff00ff'>baidu.com<p>"
# send_email.send_html(msg_to, subject, content_html) # 方法1
# send_email.send_txt_file(msg_to, subject, 'scheduler.txt') # 方法2
content="这是我使用python smtplib及email模块发送的邮件" # 正文
# send_email.send_text(msg_to, subject, content) # 方法3
python
整章节共122节
快分享给你的小伙伴吧 ~