python代码实现发送邮件

以网易邮箱为例,简单粗暴,实现代码如下:

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

sender = '***@163.com'  # 发送者
receiver = '***@qq.com'  # 接收者
sender_passwd = '******'

def send_email_with_text(from_addr, to_addr, from_addr_passwd):
    # 发送只含文本内容的邮件
    message = MIMEText('Python 邮件发送文本内容...', 'plain', 'utf-8') # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
    message['From'] = from_addr
    message['To'] = to_addr

    subject = 'Python SMTP 邮件测试'  # 邮件主题
    message['Subject'] = subject

    smtpObj = smtplib.SMTP('smtp.163.com', 25)  # 连接STMP服务器
    smtpObj.login(from_addr, from_addr_passwd)  # 用授权码登录
    smtpObj.sendmail(from_addr, to_addr, message.as_string())  # 发送邮件
    smtpObj.quit()  # 断开服务器连接

def send_email_with_html(from_addr, to_addr, from_addr_passwd):
    # 发送正文含链接的邮件
    mail_msg = """
    

Python 邮件发送测试...

https://www.python.org/

""" message = MIMEText(mail_msg, 'html', 'utf-8') # 三个参数:第一个为文本内容,第二个 html 设置超文本格式,第三个 utf-8 设置编码 message['From'] = from_addr message['To'] = to_addr subject = 'Python SMTP 邮件测试' # 邮件主题 message['Subject'] = subject smtpObj = smtplib.SMTP('smtp.163.com', 25) # 连接STMP服务器 smtpObj.login(from_addr, from_addr_passwd) # 用授权码登录 smtpObj.sendmail(from_addr, to_addr, message.as_string()) # 发送邮件 smtpObj.quit() # 断开服务器连接 def send_email_with_att(from_addr, to_addr, from_addr_passwd): message = MIMEMultipart() # 创建一个带附件的对象 message['From'] = from_addr message['To'] = to_addr subject = 'Python SMTP 邮件测试' # 邮件主题 message['Subject'] = subject # 邮件正文部分 message.attach(MIMEText('这是Python 邮件发送测试……', 'plain', 'utf-8')) # 构造附件 att = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="test.txt"' message.attach(att) smtpObj = smtplib.SMTP('smtp.163.com', 25) # 连接STMP服务器 smtpObj.login(from_addr, from_addr_passwd) # 用授权码登录 smtpObj.sendmail(from_addr, to_addr, message.as_string()) # 发送邮件 smtpObj.quit() # 断开服务器连接 send_email_with_text(sender, receiver, sender_passwd) send_email_with_html(sender, receiver, sender_passwd) send_email_with_att(sender, receiver, sender_passwd)

 

你可能感兴趣的:(Python学习)