用smtplib模块发送文本遇到的问题

import smtplib

from email.mime.text import MIMEText

sender = ‘ycl_***@126.com’

pwd = ‘********’#授权码密码

receive = ‘**********@qq.com’

msg = MIMEText(‘这是一个测试!成功啦’)

subject = ‘ycl_0204’

msg[‘From’] = sender

msg[‘To’] = receive

msg[‘Subject’] = subject
try:
sss = smtplib.SMTP_SSL(‘smtp.126.com’,465)

sss.login(sender,pwd)

sss.sendmail(sender,receive,msg.as_string())

print('发送成功!')

except Exception as e:
print(e)
注意的是:
1.当代码没有错误,但发送失败的时候,有可能是网络问题
2.当发送成功,但没有接收到有可能是被拒收或放入垃圾箱
3.login登陆时候填写的不是账户密码,是授权码密码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 导入smtplib模块和MIME模块 ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication ``` 2. 设置发件人、收件人、主题和正文 ```python sender = '发件人邮箱地址' receiver = '收件人邮箱地址' subject = '邮件主题' body = '邮件正文' ``` 3. 创建MIMEMultipart对象并设置发件人、收件人和主题 ```python message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = subject ``` 4. 创建MIMEText对象并设置正文 ```python text = MIMEText(body) message.attach(text) ``` 5. 创建MIMEApplication对象并设置附件 ```python with open('附件文件路径', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='pdf') attachment.add_header('Content-Disposition', 'attachment', filename='附件文件名.pdf') message.attach(attachment) ``` 6. 连接SMTP服务器并登录,发送邮件 ```python smtp_server = 'SMTP服务器地址' smtp_port = 25 # SMTP服务器端口号 smtp_user = 'SMTP服务器用户名' smtp_password = 'SMTP服务器密码' smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.login(smtp_user, smtp_password) smtp.sendmail(sender, receiver, message.as_string()) smtp.quit() ``` 完整代码示例: ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication sender = '发件人邮箱地址' receiver = '收件人邮箱地址' subject = '邮件主题' body = '邮件正文' message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = subject text = MIMEText(body) message.attach(text) with open('附件文件路径', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='pdf') attachment.add_header('Content-Disposition', 'attachment', filename='附件文件名.pdf') message.attach(attachment) smtp_server = 'SMTP服务器地址' smtp_port = 25 # SMTP服务器端口号 smtp_user = 'SMTP服务器用户名' smtp_password = 'SMTP服务器密码' smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.login(smtp_user, smtp_password) smtp.sendmail(sender, receiver, message.as_string()) smtp.quit() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值