Finished sendmail.py module and ists tests

This commit is contained in:
Antonio de la Rosa 2016-02-09 15:15:52 +01:00
parent 1a0d11d829
commit 726d778808
2 changed files with 62 additions and 4 deletions

View file

@ -1,5 +1,5 @@
#!/usr/bin/python3 #!/usr/bin/python3
import os
import smtplib import smtplib
import mimetypes import mimetypes
from email import encoders from email import encoders
@ -99,4 +99,60 @@ class SendMail:
return True return True
else:
outer=MIMEMultipart()
outer['Subject']=subject
outer['From']=from_address
outer['To']=COMMASPACE.join(to_address)
# Attach message text
msg=MIMEText(message, content_type)
outer.attach(msg)
for path in attachments:
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
with open(path) as fp:
# Note: we should handle calculating the charset
msg = MIMEText(fp.read(), _subtype=subtype)
elif maintype == 'image':
with open(path, 'rb') as fp:
msg = MIMEImage(fp.read(), _subtype=subtype)
elif maintype == 'audio':
with open(path, 'rb') as fp:
msg = MIMEAudio(fp.read(), _subtype=subtype)
else:
with open(path, 'rb') as fp:
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
outer.attach(msg)
self.smtp.send_message(outer)
return True

View file

@ -10,8 +10,10 @@ class TestFieldMethods(unittest.TestCase):
#self.assertEqual(phrase, 'this---is-a-crap-phrase-o---f-oh-yeah--') #self.assertEqual(phrase, 'this---is-a-crap-phrase-o---f-oh-yeah--')
self.assertTrue( s.send(config.portal_email, [config.email_test], 'This is a test', 'A message for test a simple email method', content_type='plain', attachments=[]) ) self.assertTrue( s.send(config.portal_email, config.email_test, 'This is a test', 'A message for test a simple email method', content_type='plain', attachments=[]) )
self.assertTrue( s.send(config.portal_email, [config.email_test], 'This is a test', 'A message for test a simple email method in <b>html</b>', content_type='html', attachments=[]) ) self.assertTrue( s.send(config.portal_email, config.email_test, 'This is a test', 'A message for test a simple email method in <b>html</b>', content_type='html', attachments=[]) )
self.assertTrue( s.send(config.portal_email, config.email_test, 'This is a test', 'A message for test a simple email method in <b>html</b> and attachments', content_type='html', attachments=['tests/images/image.jpg']) )
s.smtp.quit() s.smtp.quit()