Can I use this function to reliably attach a list of excel files to an email and create a secure connection to transmit said email? My python programming is self taught and I put this function together with a lot of google searches. (This function works, I use it, but I would like to have someone with more experience look it through, if possible)
Where can I improve my code? (Am I using the correct modules?)
import datetime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
sMDY = datetime.date.today().strftime('%m/%d/%y')
lpath = 'C:/Path/to/my/excel/files/'
flist = ['excelfile_1.xlsx', 'excelfile_2.xlsx']
def EMAIL_FILES(flist):
uname = 'username'
pword = 'password'
emailfrom = '[email protected]'
emailto = [
'[email protected]',
'[email protected]',
]
body = ["The information transmitted is ..."]
subject = ('Subject with date %s' % sMDY)
msg = MIMEMultipart()
msg['From'] = emailfrom
msg['To'] = ', '.join(emailto)
msg['Subject'] = subject
msg.attach(MIMEText(''.join(body)))
### ATTACH FILES
for item in flist:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(lpath + item, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % item)
msg.attach(part)
### SECURE CONNECTION
server = smtplib.SMTP('smtp.domain.com:25')
server.ehlo()
server.starttls()
server.ehlo()
server.login(uname, pword)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()