简体   繁体   中英

How do I get email attachments (.html, .txt) to show in the sent email using Python script seen below?

My email shows the attachments without displaying what they are. I have one .txt and five .html I wish to be specified. Does any one have a suggestion to fix this?

My code as follows:

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

COMMASPACE = ', '

def email_main():
sender = 'xxxxxx@gmail.com'
gmail_password = 'xxxxxx123'
recipients = ['xxx@xxx.com', 'xxxyyy@yahoo.com']

# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'VECTOR CAST AUTOMATED TEST RESULTS'
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# email message 
body = MIMEText('Test results attached.', 'html', 'text')  
outer.attach(body)  # add message body (text or html)

# List of attachments to email
emailfiles = ['VCAST Test Times.txt', \
         'AECP_MAIN_INTEGRATION_management_report.html', \
         'BECP_MAIN_INTEGRATION_management_report.html', \
         'SWITCH_BOARD_INTEGRATION_management_report.html', \
         'EVENT_MANAGER_INTEGRATION_management_report.html', \
         'EXTERNAL_ALARM_INTEGRATION_management_report.html']

# get the path of the folder this lives in 
attachments = [os.getcwd()]

# Add the attachments to the message
for file in attachments:
    try:
        for line in emailfiles:              
            fp = open(line , 'rb')            
            msg = MIMEBase('application', "octet-stream")
            msg.set_payload(fp.read()) 
            encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))

            """
            file_path = os.path.join(dir_path, f)
            msg = MIMEApplication(open(file_path, "r").read(), _subtype="txt")
            msg.add_header('Content-Disposition','attachment', filename=f)
            """
            outer.attach(msg)
    except:
        print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
        raise

composed = outer.as_string()

# Send the email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(sender, gmail_password)
text = msg.as_string()
server.sendmail(sender, recipients, composed)
server.quit()   

if __name__ == '__main__':
    email_main()

在此处输入图片说明

os.getcwd()

gives you the current directory, for example C:\\Projects\\EmailTest So

[os.getcwd()]

gives you a list, containing one string ( C:\\Projects\\EmailTest )

So the loop

for file in attachments:

is only executed once, where file=C:\\Projects\\EmailTest .

And when you finally set in the inner loop, you use file from the outer loop: (which is C:\\Projects\\EmailTest )

filename=os.path.basename(file)

You simply extract the folder name from file, ie EmailTest .

Im guessing you want the filename instead, stored in emailfiles , which in your case is line in the inner loop. And since it is already only the filanem, you can skip os.path.basename :

msg.add_header('Content-Disposition', 'attachment', filename=line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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