简体   繁体   中英

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")
        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",
        []
    )

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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM