通过.txt文件将文本发送到电子邮件

时间:2020-09-25 09:18:27

标签: python email

有什么方法可以将文本从文本文件(.txt)发送到电子邮件。我成功地将附件文本文件发送到了电子邮件,但我只想发送文本,而不是整个文件。从.txt文件中检索文本并发送。

这是我发送电子邮件附件的代码

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path

email = 'assassin@gmail.com' # Your email
password = '123abc' # Your email account password
send_to_email = 'james12@gmail.com' # Who you are sending the message to
subject = 'subject' # The subject line
message = 'ok' # The message in the email
file_location = r'C:\Users\hp\Downloads\SimpleCoin-master\SimpleCoin-master\simpleCoin\output.txt'

msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject

 # Attach the message to the MIMEMultipart object
msg.attach(MIMEText(message, 'plain'))

# Setup the attachment
filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

# Attach the attachment to the MIMEMultipart object
msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string() # You now need to convert the MIMEMultipart object to a string to send
server.sendmail(email, send_to_email, text)
server.quit()

我只想在电子邮件正文中发送文本,而不是整个文件附件

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码进行操作:

import smtplib
import os.path

email = 'assassin@gmail.com' # Your email
password = '123abc' # Your email account password
send_to_email = 'james12@gmail.com' # Who you are sending the message to
subject = 'subject' # The subject line

file_location = # File location here

with open(file_location) as f:
    message = f.read()

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = "Subject: {}\n\n{}".format(subject , message)
server.sendmail(email, send_to_email, text)
server.quit()

相关问题