无法使用sendmail发送电子邮件

时间:2018-02-12 01:32:24

标签: python email smtp sendmail

我正在尝试使用以下代码发送电子邮件,我没有看到任何错误并且消息Success! Email Sent'被打印但是我没有收到任何电子邮件?如何调试这个?关于为什么我的任何指示我没有收到电子邮件?

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib,time
import traceback
from subprocess import Popen, PIPE, call

TO = ['username@company.com', 'username@company.com' ]
CC = ['username@company.com']
SENDER = "username@company.com"
timestr = time.strftime("%m/%d/%Y at %H:%M:%S")
SUBJECT = str("Test email " + timestr)

msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = ",".join(TO)
msg['Cc'] = ",".join(CC)
msg['Content-Type'] = "text/html; charset=utf-8"
msg['Content-Transfer-Encoding'] = "quoted-printable"
msg['MIME-Version']="1.0"

EMAIL = ""
CONTENT = """\
        <html>
            <head></head>
            <style type='text/css'>
            body {
            background-color: #F8F8F8 ;
            }
            h3 {
            color: blue;
            text-align: left;
                }
            p {
            font-family: 'Avenir Next' !important;
            font-size: 20px;
            }
            table {
                 border-collapse: collapse;
            }

            table, th, td {
                  border: 1px solid black;
            }

            th {
                background-color: #99CCFF;
                color: white;
            }
            </style>
            """

REST = """\
            <body>
                {0}
            </body>
        </html>""".format(EMAIL)

CONTENT += REST
#print(CONTENT)
emailHTML = MIMEText(CONTENT, 'html')
msg.attach(emailHTML)

smtpObj = smtplib.SMTP('mail.company.com')
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('username@company.com', 'password815')

try:
    p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
    p.communicate(msg.as_string())
    print('Success! Email Sent')
except:
    print traceback.format_exc()
    print("ERROR Sending Email : Email was not sent")

smtpObj.close()

1 个答案:

答案 0 :(得分:0)

您正在经历构建smtp对象的所有痛苦,打开与它的连接,最后 - 通过外部进程发送消息?为什么呢?
您几乎就在那里,只需尝试使用您的python代码发送它。

在try块中,使用以下代码更改Popen代码:

try:
    recipients = TO + CC
    smtpObj.sendmail(SENDER, recipients, msg.as_string())
except:
    print traceback.format_exc()
    print("ERROR Sending Email : Email was not sent")
finally:
    smtpObj.quit()  # the connection stays open even if an exception was raised, thus the quit() is here