繁体   English   中英

Email 发送无附件 - Python 3.8

[英]Email sending without attachment - Python 3.8

  1. 我想在 Python 中发送附加到邮件的 .txt 文件。 目前已收到邮件,但没有任何附件。
  2. 代码如下
  3. 我已经在 PHP 中发送了电子邮件,但 Python 对我来说是全新的
  4. 该代码不返回任何错误,它只是不发送带有 email 的附件
   with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
       server = smtplib.SMTP('smtp.gmail.com', 587) 
       smtp.ehlo()
       smtp.starttls()
       smtp.ehlo()
       msg = MIMEMultipart()

       smtp.login(EMAIL_ADRESS, EMAIL_PASSWORD)
       subject = 'Log Register'

       
       filename = 'logs-to-h4wtsh0wt.txt'
       attachment = open(filename, 'rb')
       part = MIMEBase('application', 'octet-stream')
       part.set_payload(attachment.read())
       encoders.encode_base64(part)
       part.add_header('Content-Disposition', "attachment; filename= "+filename)
       msg.attach(part)
       msg = f'Subject: {subject}\n\n{Body}'
       smtp.sendmail(EMAIL_ADRESS,EMAIL_ADRESS, msg)

snakecharmerb 是对的。 您确实覆盖了消息 object ,因此丢失了您在此之前添加的所有内容。

您可以改为这样设置主题:

msg['Subject'] = "Subject of the Mail"

# string to store the body of the mail 
body = "Body_of_the_mail"
  
# attach the body with the msg instance 
msg.attach(MIMEText(body, 'plain')) 

因为您要附加一个文件,所以您还需要在发送之前将多部分消息转换为字符串:

text = msg.as_string()

smtp.sendmail(fromaddr, toaddr, text) 

当您使用MIMEMultipart()创建msg时,它会根据RFC2822为您生成消息 object 结构,该结构还为您提供FROMTO等。

msg object 还具有您可以在其文档中概述的一系列功能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM