[英]Email sending without attachment - Python 3.8
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 结构,该结构还为您提供FROM
、 TO
等。
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.