0

I am trying to send an email using python, with an attachment. Here is my code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = "name@company.com"
toaddr = "name2@company.com"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Testing Python Email - Plus Attachments"

body = "This is an automated email"

msg.attach(MIMEText(body, 'plain'))

filename = "nice.png"
attachment = open("C:\\Users\\Ben Hannah\\Documents", "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(fromaddr, "************")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

And this is what it gives back:

Traceback (most recent call last):
  File "C:\Users\Ben Hannah\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 517, in _input_type_check
    m = memoryview(s)
TypeError: memoryview: a bytes-like object is required, not 'NoneType'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Ben Hannah\AppData\Local\Programs\Python\Python36-32\lib\email\encoders.py", line 32, in encode_base64
    encdata = str(_bencode(orig), 'ascii')
  File "C:\Users\Ben Hannah\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 534, in encodebytes
    _input_type_check(s)
  File "C:\Users\Ben Hannah\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 520, in _input_type_check
    raise TypeError(msg) from err
TypeError: expected bytes-like object, not NoneType

the email sends, the mailbox recieves it and see's an attachment - but when trying to open it, it says it cant open the file.

B.Hannah
  • 3
  • 2

1 Answers1

2

You forgot to include filename in open.

filename = "nice.png"
attachment = open("C:\\Users\\Ben Hannah\\Documents", "rb")

Try,

attachment = open("C:\\Users\\Ben Hannah\\Documents\\" + filename, "rb")
balki
  • 22,482
  • 26
  • 85
  • 135
  • Hi! that makes sense thank you! Would you be able to tell me how to make this email run automatically every hour, would I use loops or recursions? – B.Hannah Sep 26 '17 at 13:34
  • I would use some scheduling tool. There are some options here for windows: https://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron – balki Sep 26 '17 at 13:38