用python发邮件、添加附件

本文介绍了使用Python的smtplib和email模块来发送邮件,详细讲解了如何添加附件,以及理解授权码和SMTP协议的工作原理。同时,还涵盖了邮件发送过程中的各种状态编码。
摘要由CSDN通过智能技术生成

python 发邮件

  1. 两个内置模块:smtplib 、email

  2. 需要了解附件以什么形式添加到邮件中(open方法、二进制、字节)

  3. 什么是授权码

  4. 能够看懂邮件发送过程中的发送编码(发送成功、发送失败、垃圾邮件等编码编号)

  5. 什么是smtp协议:

    # SMTP协议,简单邮件传输协议。它是用于从源地址到目标地址的邮件传输规范,通过SMTP协议
    # 控制邮件中转的方式。SMTP协议属于TCP/IP协议簇,它可以帮助每台计算机在发送或中转信件
    # 的时候找到下一个地址。SMTP服务器就是遵循SMTP协议发送邮件的服务器。其中涉及到SMTP认证,
    # 此认证可以使垃圾邮件的发送者没有机会散播垃圾邮件,增加SMTP认证的目的就是为了使用户避免
    # 收到垃圾邮件的骚扰。
    

python发邮件代码

import smtplib
sendAddress='xxxxxxxxx@qq.com'
passWord='xxxxxxxxxxxxxxx' #进入扣扣空间-设置-账户-开启服务(POP3/SMTP服务、IMAP/SMTP服务)-发送短信,获取授权码
# #常用邮箱服务器: 发送邮箱端口都是465
# 新浪邮箱:smtp.sina.com
# 搜狐邮箱:smtp.sohu.com
# 126邮箱:smtp.126.com
# 163邮箱:smtp.163.com
# qq邮箱:smtp.qq.com
server=smtplib.SMTP_SSL('smtp.qq.com',465)
loginResult=server.login(sendAddress,passWord)
print(loginResult)  #(235, b'Authentication successful')表示登录成功

from email.mime.text import MIMEText
#MTMEText不能被用来构造信息。但是MIMEText不能添加附件
#构建邮件正文
content="""
邮件正文内容
"""
#将正文添加到邮件消息中
#plain:子内容的类型
#utf-8为Unicode编码
msg=MIMEText(content,'plain'</
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python发送邮件并附加超大附件可以使用smtplib和email库。下面是一个简单的示例代码: ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders def send_email(sender_email, sender_password, receiver_email, subject, message, attachment_path): # 创建邮件对象 msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = receiver_email msg['Subject'] = subject # 添加邮件正文 msg.attach(MIMEText(message, 'plain')) # 添加附件 attachment = open(attachment_path, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path) msg.attach(part) # 发送邮件 server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(sender_email, sender_password) server.sendmail(sender_email, receiver_email, msg.as_string()) server.quit() # 使用示例 sender_email = "your_email@gmail.com" sender_password = "your_password" receiver_email = "recipient_email@gmail.com" subject = "Email with Large Attachment" message = "Please find the attached file." attachment_path = "path_to_your_attachment" send_email(sender_email, sender_password, receiver_email, subject, message, attachment_path) ``` 请确保你已经安装了smtplib和email库,可以使用以下命令进行安装: ``` pip install secure-smtplib pip install email ``` 注意,这个示例使用了Gmail的SMTP服务器,如果你使用其他邮箱,请根据相应的SMTP服务器和端口进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值