简体   繁体   English

Email 发送无附件 - Python 3.8

[英]Email sending without attachment - Python 3.8

  1. I want to send a.txt file attached to the mail in Python.我想在 Python 中发送附加到邮件的 .txt 文件。 Currently the mail is received but without any attachment.目前已收到邮件,但没有任何附件。
  2. Code bellow代码如下
  3. I've sent emails in PHP but Python is completely new to me我已经在 PHP 中发送了电子邮件,但 Python 对我来说是全新的
  4. The code doesn't return any errors, it simply doesn't send the attachment with the email该代码不返回任何错误,它只是不发送带有 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 is right. snakecharmerb 是对的。 You are indeed overriding the message object and therefore losing everything you add before that point.您确实覆盖了消息 object ,因此丢失了您在此之前添加的所有内容。

You can instead set the subject like this:您可以改为这样设置主题:

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')) 

Because you are attaching a file you will also need to convert the multipart message into a string before sending:因为您要附加一个文件,所以您还需要在发送之前将多部分消息转换为字符串:

text = msg.as_string()

smtp.sendmail(fromaddr, toaddr, text) 

When you created msg with MIMEMultipart() it generated the message object structure for you as per RFC2822 which also gives you FROM , TO , etc.当您使用MIMEMultipart()创建msg时,它会根据RFC2822为您生成消息 object 结构,该结构还为您提供FROMTO等。

The msg object also has a bunch of functions you can run outlined in its docs msg object 还具有您可以在其文档中概述的一系列功能

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

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