I have code sending email in Python:
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formatdate
SERVER_ADDR = 'smtp.gmail.com'
def sendMail(dir, fromAddr, toAddr, subject, text, files):
msg = MIMEMultipart()
msg['From'] = fromAddr
msg['To'] = toAddr
msg['Date'] = datetime.date.today()
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 {}'.format(os.path.basename(file)))
msg.attach(part)
smtp = smtplib.SMTP(SERVER_ADDR,587)
smtp.sendmail(fromAddr,toAddr,msg.as_string())
smtp.close()
return 0
def main(argv):
files = [argv[1]]
sendMail(myemail,myemail,"Zalacznik","Tekst maila bla bla bla.",
files) # I replaced my email here
return 0
if __name__=="__main__":
sys.exit(main(sys.argv))
I've got error:
TypeError: sendMail() missing 1 required positional argument: 'files'
What is wrong with my code?
[EDIT]: Ok I've removed dir from signature, but I have another error:
TypeError: expected bytes, not builtin function or method
Error is in line encoders.encode_base64(part)
.
This question has nothing to do with sending emails, or attachments.
The signature of the sendMail
function has as the first positional argument dir
- although you don't use that anywhere in the function. However, when you call the function, you seem to have missed out that argument: the first parameter you send is an email, so is presumably intended to be fromAddr
.
You probably just want to remove that argument from the definition.
To put the definition and call of sendMail
alongside one another:
def sendMail(dir, fromAddr, toAddr, subject, text, files):
# | | | | | !
sendMail(myemail, myemail, "Zalacznik", "Tekst maila bla bla bla.", files)
As Python interprets the arguments positionally it tells you you're missing the last one, files
, but I would say you're really missing the first one, dir
.
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.