Why does my Python email script have an error? - python

from smtplib import SMTP_SSL as SMTP
from email.MIMEText import MIMEText
import traceback
#from_field is a dictionary with smtp_host, name, email, and password
def send(from_field, to_email):
subject = 'how do you know it'
body="""\
hello there
"""
try:
msg = MIMEText(body, 'plain')
msg['Subject']= subject
msg['From'] = from_field['name'] + ' <'+from_field['email']+'>'
print msg
conn = SMTP(from_field['smtp'])
conn.set_debuglevel(False)
conn.login(from_field['email'],from_field['password'])
try:
conn.sendmail(from_field.email,[to_email], msg.as_string())
pass
finally:
conn.close()
except Exception, exc:
traceback.print_exc()
sys.exit( "mail failed; %s" % str(exc) ) # give a error message
I get this error message when I run it:
AttributeError: 'dict' object has no attribute 'email' on the conn.sendmail line

from_field is a dictionary. That line should be:
conn.sendmail(from_field['email'], to_email, msg.as_string())

Related

Using try-except sentenec in python with tenacity doesn't retry as expected

Hi there i'm trying to use tenacity for sending an email, the script is the following:
from tenacity import retry, stop_after_attempt
from smtplib import SMTP_SSL, SMTP
#retry(stop = stop_after_attempt(7))
def email_tables(mails_to_list, smtp_host, smtp_port, smtp_user, smtp_pass, tables):
try:
#ENVIO DE DATOS
#Lista de mails a enviar la info
mails_to = mails_to_list
msg = (f"From: {smtp_user}\r\nSubject: Daily app status\r\nTo: %s\r\n\r\n" % (", ".join(mails_to)))
for table in tables:
msg = msg + table + "\r\n\r\n"
print(msg)
with SMTP(host = smtp_host, port = smtp_port) as smtp:
smtp.starttls()
smtp.login(user = smtp_user, password = smtp_pass)
smtp.sendmail(from_addr = smtp_user, to_addrs = mails_to, msg = msg)
smtp.quit()
except Exception:
print(Exception)
The thing is that if i run email_tables(vars) the output runs only once the method and then exits the script.
If i remove the try-except sentence and don't print the Exception the script runs 7 times as expected and then raises the error.
I don't know what i'm doing wrong here in order for retry to work. Later i would like to save a log in a file when exception is raised, ideally with how many times it failed.
Thanks in advance
Seems that all i needed to do is add a raise sentence with the exception for retry to be able to read it. Final code:
from tenacity import retry, stop_after_attempt
from smtplib import SMTP_SSL, SMTP
#retry(stop = stop_after_attempt(7))
def email_tables(mails_to_list, smtp_host, smtp_port, smtp_user, smtp_pass, tables):
try:
#ENVIO DE DATOS
#Lista de mails a enviar la info
mails_to = mails_to_list
msg = (f"From: {smtp_user}\r\nSubject: Daily app status\r\nTo: %s\r\n\r\n" % (", ".join(mails_to)))
for table in tables:
msg = msg + table + "\r\n\r\n"
print(msg)
with SMTP(host = smtp_host, port = smtp_port) as smtp:
smtp.starttls()
smtp.login(user = smtp_user, password = smtp_pass)
smtp.sendmail(from_addr = smtp_user, to_addrs = mails_to, msg = msg)
smtp.quit()
except Exception:
print(Exception)
raise(Exception)

Send mail using python and html

I am trying to obtain a result set from SQL query and add it to my email template which is an HTML file.
Two Functions:
One for mail summary and the other one to change the email body.
I am using smtplib and email packages from python to send out a mail.
#send a email
from fileOps import fileOps
from dbOps import dbOps
import smtplib
from smtplib import SMTP, SMTPException
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mailFrom = ''
password = ''
mailTo = ''
mailServer = 'smtp.gmail.com'
port = 587
s = smtplib.SMTP(mailServer,port)
#function for email summary
def emailSummary():
try:
#security
s.starttls()
s.login(mailFrom,password)
#for fetching all the records
dbObj = dbOps()
db = dbObj.connectDB()
sql = "SELECT DISTINCT CASE_MASTER.AGREEMENTID, CASE_MASTER.NO_OF_FILES FROM " \
"CASE_MASTER LEFT JOIN CASE_FILE_STATUS ON CASE_FILE_STATUS.MOVED_TO_AWS_FLAG = CASE_MASTER.MOVED_TO_AWS_FLAG " \
"AND CASE_FILE_STATUS.MOVED_TO_AWS_Date AND CASE_MASTER.MOVED_TO_AWS_FLAG IS NOT NULL " \
"WHERE CASE_FILE_STATUS.MOVED_TO_AWS_FLAG = 1 AND CASE_FILE_STATUS.MOVED_TO_AWS_Date IS NOT NULL"
resultSet = dbObj.readData(db, sql)
getEmailBody(resultSet)
emailBody = getEmailBody(resultSet)
s.sendmail(mailFrom, mailTo,emailBody)
s.quit()
# print("Email Successfully sent !!! ")
except smtplib.SMTPException as e :
print(e)
#function to get emailBody
def getEmailBody(resultSet):
try:
htmlTemplate = open('summaryTemplate.html', 'r')
alert_msg = MIMEText(htmlTemplate.read(), "html", "utf-8")
html = htmlTemplate.read()
part1 = MIMEText(html, 'html')
part2 = """<table>
% for r in resultSet:
<tr>
% for cell in r:
<td>${cell}</td>
% endfor</tr>
% endfor</table>""".format(**locals())
msg = MIMEMultipart('alternative')
msg['Subject'] = "HERO_FC_DM_DB"
msg['From'] = mailFrom
msg['To'] = mailTo
msg.attach(part1)
except Exception as e:
print(e)
emailSummary()
I am getting the row but not getting the content from that row
['81173'] 'cell'
File "C:\Users\sailee.pawar\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 858, in sendmail
esmtp_opts.append("size=%d" % len(msg))
'cell'
TypeError: object of type 'NoneType' has no len()
I am getting the above error
Traceback (most recent call last):
line 68, in emailSummary()
line 37, in emailSummary
s.sendmail(mailFrom, mailTo,emailBody)
line 858, in sendmail esmtp_opts.append("size=%d" % len(msg))
'cell'
TypeError: object of type 'NoneType' has no len()
expected o/p :
['81173']
'file1.jpg'
'file2.txt'

Why email is not being send to CC list?

I have the following code where the Cc email list is not working meaning emails are not received to the folks/groups in Cc list,email to To list is working,I just can't figure out what is wrong?any guidance on how to debug and fix it?
import time,smtplib
import pprint,logging,os,time,json
from subprocess import Popen, PIPE, call
from pprint import pprint
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
email = 'username2#company.com'
gerriturl = ""
def sendEmail2(type,data):
global originalchange
global gerriturl,email,username1
body = '''%s''' % (data)
#msg = MIMEMultipart(body)
msg = MIMEMultipart()
sender = 'techci#company.com'
receivers = []
cc = ['username1#company.com']
REPLY_TO_ADDRESS = 'embedded-tech-integrators#group.company.com'
if type =='failure':
print("Inside failure email %s"%email)
b = '\U0001F6A8'
print("b.decode('unicode-escape')")
receivers.append('username2#company.com')
#receivers.append(email)
print('%s'%receivers)
msg['Subject'] = '%s AUTO FAILED FOR GERRIT %s :PLEASE TAKE IMMEDIATE ACTION!!!'%(b.decode('unicode-escape'),gerriturl)
msg['From'] = sender
msg['To'] = ', '.join(receivers)
msg['Cc'] = ', '.join(cc)
msg["Content-Type"] = "text/html"
try:
mail = smtplib.SMTP('relay.company.com', 25)
msg.attach(MIMEText(body, 'html'))
msg.add_header('reply-to', REPLY_TO_ADDRESS)
print('Email sent successfully %s %s'%(receivers,cc))
except Exception as e:
logger.error('Problem sending email')
logger.error('%s' % e)
def main():
data = "THIS IS A TEST EMAIL"
sendEmail2('failure',data)
if __name__ == "__main__":
main()
The important thing is to pass the complete list of recipient email addresses to the sendmail() method - you need to concatenate the email addresses for the To, CC and BCC fields into a single list, not a string.
import smtplib
def send_email(subject, body_text, emails_to, emails_cc=[], emails_bcc=[]):
# Configuration
host = "localhost"
port = 1025
from_addr = "nobody#somewhere.com"
# Build the email body
body = "\r\n".join([
"From: %s" % from_addr,
"To: %s" % ', '.join(emails_to),
"CC: %s" % ', '.join(emails_cc),
"Subject: %s" % subject ,
"",
body_text
])
# Prepare the complete list of recipient emails for the message envelope
emails = emails_to + emails_cc + emails_bcc
# Connect to the server
server = smtplib.SMTP(host, port)
# Send the email
server.sendmail(from_addr, emails, body)
# Close the server connection
server.quit()

in python how to find sending email failed ( deliver status )

I want to print sending fail when mail unable to deliver
condition: when Email format is correct but invalid email
#api.multi
def confirm_submit(self):
print 'method calling done'
import smtplib
from random import randint
abcd=(randint(2000, 9000))
print abcd
otp=str(abcd)
self.otpp = otp
receivers = self.reg_email
sender = 'asif#gmail.com'
# receivers = 'asif#gmail.com'
message = """Welcome to IB =
"""
smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(user="asif#gmail.com", password="password")
print "Successfully sent email"
Just try this :
try:
smtpObj.starttls()
smtpObj.login(login, password)
smtpObj.sendmail(msg['From'], recipients_emails, msg.as_string())
print("success")
except Exception as e:
print("failed", e)

Python SMTP what is wrong with the syntax?

I am very new to this whole Python 3.4 syntax and need some help working out this portion of my SMTP mailer. Anyways, if you could help that would be great! Below is the code in Python script.
print ('SMTP Mailbox Spammer v1')
import smtplib
smtpObj = smptlib.SMTP( [smtp.gmail.com [ 465]] )
receive = str(input('Receiver: '))
subject = str(input('Subject: '))
message = str(input('Message: '))
sender = 'johnappleseed3113#gmail.com'
receivers = ['to#todomain.com']
message = """From: From Person <johnappleseed3113#gmailc.om>
To: To Person <"""receive""">
Subject: """subject"""
"""message"""
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
you should remove tab below.
sender = 'johnappleseed3113#gmail.com'
receivers = ['to#todomain.com']
message = """From: From Person
To: To Person <"""receive""">
Subject: """subject"""
"""message"""
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"

Categories