Sending my first email in Python SMTP - using "with" is invalid syntax? - python-3.x

I'm following a class online and I'm doing as the instructor does. They used a with block for this bit of code to send the email, but it gives me an SyntaxError. I don't understand what I'm doing wrong here, I followed the exact same steps.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
#Replaced email, name, & password w/ filler
message = MIMEMultipart()
message["from"] = "First_Name Last_Name"
message["to"] = "email#email.com"
message["subject"] = "This is a test"
message.attach(MIMEText("Body")
with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login("email#email.com", "password1234")
smtp.send_message(message)
print("Sent...")
Here's the error I get:
File "c:\Users\Mofongo\Google Drive\HelloWorld\app.py", line 11
with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp:
^
SyntaxError: invalid syntax

You are missing a closing parenthesis in the message.attach(MIMEText("Body")).

Related

Python smtplib.SMTPRecipientsRefused

I been trying to make a python program that sends email but i keep getting this error
Traceback (most recent call last):
File "C:\Users\25194\PycharmProjects\Gmail\Yo.py", line 25, in <module>
smtp.sendmail(email_sender, email_password, em.as_string())
File "C:\Users\25194\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 901, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'google login': (553, b'5.1.3 The recipient address <Gmail app password> is not a valid RFC-5321\n5.1.3 address. Learn more at\n5.1.3 https://support.google.com/mail/answer/6596 k9-20020a7bc409000000b003c6bd91caa5sm17184983wmi.17 - gsmtp')}
The code is
from email.message import EmailMessage
import ssl
import smtplib
email_sender = 'oropyt32#gmail.com'
email_password = 'google login'
email_reciver = 'milkiwasihunpro#gmail.com'
subject = 'Check mate'
body = """
I am making this sending this isnt it cool oro
"""
em = EmailMessage()
em['From'] = email_sender
em['TO'] = email_reciver
em['Subject'] = subject
em.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
smtp.login(email_sender, email_password)
smtp.sendmail(email_sender, email_password, em.as_string())
i am having hard time figuring out how to fix it
... b'5.1.3 The recipient address is not a valid RFC-5321\n5.1.3 address. ...
Obviously you are using a password in place where an email is expected
smtp.sendmail(email_sender, email_password, em.as_string())
From the documentation of sendmail:
SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
So you give the email_password where to_addrs is expected. No wonder that it complains about your password used as recipient. You probably meant to use email_reciver instead.

Issues with smtplib sending mails

I tried following a youtube video on how to use smtplib to send emails, however whenever I try to send anything it gives me this error.
in alert_mail
msg.set_content(body)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/email/message.py", line 1162, in set_content
super().set_content(*args, **kw)
TypeError: super(type, obj): obj must be an instance or subtype of type
I really don't know why as I followed the video very closely, only changing the Gmail credentials and passwords to my own test accounts.
import smtplib
from email.message import EmailMessage
def alert_mail(subject, body, to):
msg = EmailMessage
msg.set_content(body)
msg["subject"] = subject
msg["to"] = to
user = "helios.alert.system#gmail.com"
msg["from"] = user
password = #2 way encription password would be here, but thats not the issue
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(user,password)
server.send_message(msg)
server.quit()
alert_mail("Hey","Hey this is my first com method" , "helios.alert.system#gmail.com") # sends email to itself, doesn't work even when some different address is entred
Any advice will be appreciated!
The video: https://www.youtube.com/watch?v=B1IsCbXp0uE
You should add an opening and closing parenthesis to the msg = EmailMessage line, remember that EmailMessage is an object, so you must use the correct syntax for creating one. This code below should work:
server = smtplib.SMTP(GMAIL_SERVER, GMAIL_PORT)
server.starttls()
server.login(EMAIL_SOURCE, PWD_SOURCE)
msg = EmailMessage()
msg['From'] = EMAIL_SOURCE
msg['To'] = TO_EMAIL
msg['Subject'] = YOUR_SUBJECT
msg.set_content(bodyOfMail)
server.send_message(msg)
del msg
server.quit()

Gmail account. Python 3.8 idle script. Error: smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first

I'm doing an exercise on writing a module in python 3.8 idle (Mac) to send emails from my gmail account. It is giving me the error:
smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first.
THE COMPLETE RUNNING RESULT:
= RESTART: /Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py
person_name
Thank you for sharing!
Traceback (most recent call last):
File "/Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py", line 58, in <module>
main()
File "/Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py", line 51, in main
s.send_message(msg)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 970, in send_message
return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 871, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first. c18sm12642612wmk.18 - gsmtp', 'xxxxx#gmail.com')
The first two lines (person_name Thank you for sharing!) are from the 'message.txt' file.
MY CODE IS:
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_addr = 'xxxxxg#gmail.com'
password = 'xxxxxxxxxxx'
smtp_server = 'smtp.gmail.com'
def get_contacts(self):
names = []
emails = []
with open(self, 'r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0])
emails.append(a_contact.split()[1])
return names, emails
def read_template(self):
with open(self, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
def main():
names, emails = get_contacts('contacts.txt') # read contacts
message_template = read_template('message.txt')
# set up the SMTP server
s = smtplib.SMTP_SSL(smtp_server)
s.ehlo()
s.connect(smtp_server,465)
s.login(from_addr, password)
# For each contact, send the email:
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message = message_template.substitute(person_name = name.title())
# prints out the message body for our sake
print(message)
# setup the parameters of the message
msg['From'] = from_addr
msg['To'] = email
msg['Subject'] = 'This is TEST'
# add in the message body
msg.attach(MIMEText(message, 'plain', 'utf-8'))
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
if __name__ == '__main__':
main()
I saw this code in one of the questions asked here and it looked great to me as an example, so I wanted to try it out. But my problem turns out different than what the original one had. From the running result, it looks like the """print(message)""" command is successfully loaded. The problem occurs at """s.send_message(msg)""". I checked online several similar cases but couldn't find answer that suits this condition.
Really grateful to any help :)
Acorus
Problem solved thanks to Konrad
Swapping the .ehlo() with .connect()
& Changing the password to an authentication code generated from gmail setting 2-step verification app password. I used "mail" & "mac" to generate the verification code.
While I have never used Python to send emails, I've spent some time communicating with SMTP servers via Telnet.
You need to connect to the server first, then send EHLO, then authenticate and finally send the message. Your code seems to try sending EHLO before connecting to the server.
Try swapping those two lines.

Sending mail with Python's smtplib returns "501 5.1.3 Invalid address"

Consider this code extract:
import smtplib
from email.message import EmailMessage
body = "some content"
email = EmailMessage()
email.set_content(body, subtype='html')
to = "you#work.com"
email['From'] = "me#work.com"
email['To'] = to
email['Cc'] = ""
email['Bcc'] = ""
email['Subject'] = "Hello"
smtp_connection = smtplib.SMTP("smtp.work.com", 25)
status = smtp_connection.send_message(email)
print(str(status))
print(to)
When running the code, the mail actually arrives correctly at the destination, but the print statement returns this: {'': (501, b'5.1.3 Invalid address')}
I've seen other posts around on the internet with similar error message, where it's been a case of malformed recipient addresses causing the message not to be delivered, but in my case the emails actually do get delivered correctly. I've also made sure that the email address output'ed by the last print statement is actually correct.
Any input on how to debug this further will be appreciated.
I believe I found the answer. Looks like empty "CC" and "BCC" values causes the error. When I removed these I got rid of the error message.
If your Cc and Bcc is also empty, it is no need to attach it in email[]

Python's Email Message library output not getting accepted by Outlook 365 when i have a named attachments from

I've created a sample function to test sending emails with an attached html file, which i intend to use for reporting on automated test runs in the future (replacing an existing external powershell script). Note that I'm attaching the html file, not using the html as inline text in the body. I'm using our company's mailgun smtp account service to send the email.
I seem to have an issue with Outlook 365 (web hosted - uses the outlook.office.com domain) either rejecting or blocking the sent email, but interestingly the same email is received and accepted by my personal hotmail address (outlook.live.com domain). I've found Outlook 365 blocks or does not accept the email when I attempt to name the file in the email message object. But if I don't name it, it will come through (with a default name of "ATT00001.htm" ).
My code for this is below but they key line seems to be
msg.add_attachment(open_file.read(), maintype='text', subtype='html', filename=filename)
If I drop the filename key it works (but with a default assigned filename) e.g.
msg.add_attachment(open_file.read(), maintype='text', subtype='html')
I have a suspicion there is something in the attachment's header or Content-disposition that Outlook 365 doesn't agree with, but i'm not sure what it is or how to work around.
I'm using the following (Python 3.6.5, on Windows 10 machine, smtplib and email.message seem to be built in)
Here is the code:
import smtplib
from email.message import EmailMessage
import os
def send_mail():
MAILGUN_SMTP_LOGIN = "<my company's mailgun login>"
MAILGUN_SMTP_PASSWORD = "<my company's mailgun password>"
fromaddr = "muppet#sharklasers.com" # the from address seems to be inconsequential
toaddr = ['me#mycompanysdomainusingoffice365.com.au', 'me#hotmail.com']
msg = EmailMessage()
msg.preamble = 'This is preamble. Not sure where it should show in the email'
msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Subject'] = 'Testing attached html results send'
msg.set_content(""" This is a test of attached html """)
filename = 'api_automatedtests_20180903_1341.html'
filepath = os.path.abspath('D:/work/temp/api_automatedtests_20180903_1341.html')
open_file = open(filepath, "rb")
# msg.make_mixed()
msg.add_attachment(open_file.read(), maintype='text', subtype='html', filename=filename)
# msg.add_attachment(open_file.read(), maintype='text', subtype='html')
server = smtplib.SMTP(host="smtp.mailgun.org", port=587)
server.ehlo()
server.starttls()
server.login(MAILGUN_SMTP_LOGIN, MAILGUN_SMTP_PASSWORD)
server.set_debuglevel(1)
server.send_message(msg)
server.quit()
if __name__ == "__main__":
send_mail()
What I've tried
Tried sending with the same code using a textfile (with appropriate types). e.g.
msg.add_attachment(open_file.read(), maintype='text', subtype='plain', filename=filename)
Result: This works as expected (comes through with the given name - the filename is a string variable e.g. testfile.txt)
adding msg.make_mixed() to make sure it is identified as a multipart message. Result: No effect
Turning on the smtp debug level 1, Result: Mailgun says that everything has worked fine (and the messages do appear as expected in my hotmail account)
Not using the filename key in the msg.add_attachment call.
Result: This works the attachment comes through at ATT00001.htm
Interestingly the default name is *.htm while the filename I'm trying to use is *.html
Tried using a filename with *.htm and a subtype of 'htm' (instead of html)
Result: Same as for html (received on hotmail but not on outlook 365)
Tried using the generic types of maintype=''application', subtype='octet-stream'.
e.g. msg.add_attachment(open_file.read(), maintype='application', subtype='octet-stream', filename=filename)
Result: Same as for html (received on hotmail but not on outlook 365)
Tried using mimetypes.guess as shown in this link
https://docs.python.org/3.6/library/email.examples.html
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
with open(path, 'rb') as fp:
msg.add_attachment(fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename)
Result: It's determined as maintype='text', subtype='html' and I get the same result as with my original code (ie arrives in hotmail but blocked by 365).
Checking my spam and clutter folders - was not there
Any suggestions on why the use of filename would be breaking it?
Update
After sending to a other email addresses with various providers I discovered:
1) muppet#sharklasers.com was not a trusted sender (can change this)
2) I discovered the attachment was being flagged as unsafe. The html file comes from pytest's html report with the single file option. It contains javascript for row expanders. Gmail warns the attachment may not be safe (office 365 just straight out blocks the email altogether).
Not sure how to work around 2). I can email the same file to myself between outlook 365 and gmail and vice versa and the file doesn't get blocked. It only get's blocked when I use the above script using python's libraries and Mailgun SMTP. I suspect there is something I need to change in the email header to get around this. But I don't know what.
There seems to be some connection between trying to add the filename and the attachment being marked as unsafe
Okay I figured it out. The problem was the content-type needed to include "name=filename" in it's value.
Also I needed to use maintype='multipart', subtype='mixed'.
I have 2 solutions.
solution 1
import smtplib
from email.message import EmailMessage
import os
def send_mail(body_text, fromaddr, recipient_list, smtp_login, smtp_pass, file_path):
msg = EmailMessage()
msg.preamble = 'This is preamble. Not sure where it should show'
msg['From'] = fromaddr
msg['To'] = ', '.join(recipient_list)
msg['Subject'] = 'API Testing results'
msg.set_content(body_text)
filename = os.path.basename(file_path)
open_file = open(file_path, "rb")
msg.add_attachment(open_file.read(), maintype='multipart', subtype='mixed; name=%s' % filename, filename=filename)
server = smtplib.SMTP(host="smtp.mailgun.org", port=587)
server.ehlo()
server.starttls()
server.login(smtp_login, smtp_pass)
server.send_message(msg)
server.quit()
if __name__ == "__main__":
smtp_login = "<my smtp login>"
smtp_pass = "<my smtp password>"
recipient_list = ['user1#mycompany.com.au', 'user2#mycompany.com.au']
file_path = os.path.abspath('D:/work/temp/api_automatedtests_20180903_1341.html')
body_text = "test results for 03/09/2018 "
fromaddr = 'autotesting#mycompany.com.au'
send_mail(body_text=body_text, recipient_list=recipient_list, smtp_login=smtp_login, smtp_pass=smtp_pass,
file_path=file_path)
solution 2 (according to the documentation using the email.mime libraries is a legacy solution and the EmailMessage method is supposed to be used in preference.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
def send_mail(body_text, fromaddr, recipient_list, smtp_login, smtp_pass, file_path):
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ', '.join(recipient_list)
msg['Subject'] = "Sending API test results"
msg.attach(MIMEText(body_text, 'plain'))
filename = os.path.basename(file_path)
attachment = open(file_path, "rb")
part = MIMEBase('multipart', 'mixed; name=%s' % filename)
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP(host="smtp.mailgun.org", port=587)
server.starttls()
server.login(smtp_login, smtp_pass)
text = msg.as_string()
server.set_debuglevel(1)
server.sendmail(fromaddr, recipient_list, text)
server.quit()
if __name__ == '__main__':
smtp_login = "<my smtp login>"
smtp_pass = "<my smtp password>"
recipient_list = ['user1#mycompany.com.au', 'user2#mycompany.com.au']
file_path = os.path.abspath('D:/work/temp/api_automatedtests_20180903_1341.html')
body_text = " Api test results for 03/09/2018 "
fromaddr = "autotest#mycompany.com.au"
send_mail(body_text=body_text, fromaddr=fromaddr, recipient_list=recipient_list, smtp_login=smtp_login, smtp_pass=smtp_pass,
file_path=file_path)

Resources