使用Python smtplib发送邮件时发生权限被拒绝错误

时间:2011-06-15 10:55:48

标签: python smtp sendmail smtplib

我正在尝试使用Python 3.2发送邮件。我的代码如下:

#from email import Encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
import os
import smtplib
from base64 import encode
from email import encoders

def sendMail(to, subject, text, files=[],server="smtp.mydomain.com"):
    assert type(to)==list
    assert type(files)==list
    fro = "From <myemail@mydomain.com>"

    msg = MIMEMultipart()
    msg['From'] = fro
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    smtp = smtplib.SMTP_SSL(server, 465)
    smtp.ehlo()
    smtp.set_debuglevel(1)
    smtp.ehlo()
    smtp.login("myemail@mydomain.com", "mypassword")
    smtp.ehlo()
    smtp.sendmail(fro, to, msg.as_string() )
    smtp.close()
    print("Email send successfully.")

sendMail(
        ["recipient"],
        "hello","cheers",
        []
    )

它给了我以下错误:

raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (501, b'5.7.1 <myemail@mydomain.com>... Permission denied', 'myemail@mydomain.com')

有人知道如何解决这个问题吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

如错误所示:在尝试使用connect实例之前,需要调用smtplib.SMTP_SSL方法。 smtplib.SMTP_SSL不会自动连接(smtplib.SMTP也不会。)