Question

this is my first post so let me know if there are any common courtesies I should know about.

I just started programming 8 months ago, so I am fairly new. I have been doing some projects to get better. A project I'm working on now creates an Excel sheet from inputted data. It's in Python, which I just started learning a couple of weeks ago. I'm attempting to embed part of this Excel sheet into an email, sent from my school address. I have spent hours looking this up, and to no avail.

There are two problems I am asking for help with:

1) The following code works for sending email from GMail, but not my school account. Unfortunately, I have been having a problem setting up outgoing email for this account on my iPhone as well. It may be related? Would anyone have idea why this code doesn't work?

import smtplib
from email.MIMEText import MIMEText

LOGIN = 'myemailaddress'
PASSWORD = 'mypassword'


def send_email(subject, message, from_addr=LOGIN, to_addr=LOGIN):
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr

    server = smtplib.SMTP('myhost',465)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(LOGIN,PASSWORD)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.close()


if __name__=="__main__":
    send_email('test', 'This is a test email', "myemailaddress", "myemailaddress")

2) Excel has an option of saving a sheet as a HTML. When doing so, I copy and pasted the HTML source and emailed it as an attachment. Unfortunately, the colored text did not transfer over. Does anyone know of a better way of using Python to send an excel sheet embedded in an email?

Thanks for your help!

Was it helpful?

Solution

More information is needed to determine the actual error. To obtain this, turn on debug logging for the smtplib module, you can do this by adding the following line before ehlo().

server.set_debuglevel(True)

If myhost is the school's mail server, then the problem is most likely that the school mail server is not listening on port 465. If myhost is Google's mail server then most likely port 465 (SMTPS) is being blocked by the school network.

Research how non-text files and content are included in e-mail (i.e. MIME attachments). If you are wanting to attach the html to the e-mail but if the intent is just to send the Excel spreadsheet then attach the spreadsheet - there is no need to convert it to HTML. Here is a StackOverflow post on the code to do so: How to send email attachments with Python

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top