I developed an email system for my client by using email.mime library. I works very well for some mail clients. For example on gmail I can see html body and attachment file but on yahoo I get an empty email. Here is the code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
import email.charset
from email import Encoders
def buildEmail(from_email, to_email, subject, text_msg, html_msg, attach_pdf_file):
"""
This function build a body for text/html message and if attachment file provide
then it will attach it too with email.
"""
# Create message container - the correct MIME type is multipart/alternative.
msgRoot = MIMEMultipart('alternative')
msgRoot['Subject'] = subject
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgRoot.epilogue = ''
# Record the MIME types of both parts - text/plain and text/html.
text_part = MIMEText(text_msg, 'plain')
msgRoot.attach(text_part)
if html_msg is not None and html_msg != '':
html_part = MIMEText(html_msg, 'html')
msgRoot.attach(html_part)
# Attach a file if provided
if attach_file is not None and attach_file != '':
fp = open(attach_pdf_file, 'rb')
part = MIMEBase('application', 'pdf')
part.set_payload( fp.read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename="%s"% os.path.basename(attach_pdf_file))
msgRoot.attach(part)
fp.close()
s = smtplib.SMTP('localhost')
s.sendmail(from_email, to_email, msgRoot.as_string())
s.quit()
Any idea where am I making a mistake?
I see several problems with this code that should prevent it from working at all on Python 2.x.
1) You don’t define
attach_fileanywhere, so this line raises an exception:Did you mean
attach_pdf_file? Changingattach_filetoattach_pdf_filecorrects that exception.2) Maybe you just left it out of your code sample, but you call a function from
os.path, but you neverimport osanywhere in your script. Adding that corrects that exception.Once those problems are corrected, running the script on my system with the
fromaddress as a gmail address raises this exception:I don’t have an SMTP server configured locally on this machine, which explains why I get the error I do. In your case, if the email is sending properly, but only for some email providers, it could be because an email provider realises that even though the address is Yahoo, the SMTP server isn’t and thus refuses the email. It’s just a hunch, but it might explain it (if this weren’t the case, it would be even easier for anyone to send an email “from” any address).