开发者

Permission Denied error while sending mail using Python smtplib

I am trying to send mail using Python 3.2. My code is as follows:

#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")
        par开发者_如何学编程t.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",
        []
    )

It gives me following error:

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

Does anybody know how to solve this problem?

Thanks in advance.


As the error says: you need to call the connect method on the smtplib.SMTP_SSL instance before you try to use it. smtplib.SMTP_SSL does not automatically connect (and neither does smtplib.SMTP.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜