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)
Related
I'm new to python, I'm working with python 3. I need to send an email with generated message. Everything is ok with message (I can print it) but somehow in that configuration, with that def-blocks emails aren't sent. What am I doing wrong? I don't get any error notifications.
import random
import string
import smtplib
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from#smtp.mailtrap.io"
receiver = "to#smtp.mailtrap.io"
def randomString(stringLength=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
def randomMessage():
random_string1 = randomString()
random_string2 = randomString()
message = f"""\
Subject: {random_string1}
To: {receiver}
From: {sender}
{random_string2}"""
return message
def main():
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
message = randomMessage()
#print(message)
server.sendmail(sender, receiver, message)
if __name__ == '__main__':
main()
Problem was in message type. I changed it to MIMEText and it works now.
import random
import string
import smtplib
from email.mime.text import MIMEText
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from#smtp.mailtrap.io"
receiver = "to#smtp.mailtrap.io"
def randomString(stringLength=10):
lettersDigits = string.ascii_lowercase + "0123456789"
return ''.join(random.choice(lettersDigits) for i in range(stringLength))
def makeMessage(subject, content):
message = MIMEText(content)
message["Subject"] = subject
message["From"] = sender
message["To"] = receiver
return message
def randomMessage():
return makeMessage(randomString(), randomString())
def sendMessage(message):
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())
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()
I have tested this piece of code and it sends the email successfully, it tends to leave the subject fields, cc and bcc fields empty as seen in the photo.
import smtplib
gmail_user = 'dummy#gmail.com'
gmail_password = 'password'
sent_from = 'dummy#gmail.com'
to = ['receiver#gmail.com']
subject = 'OMG Super Important Message'
body = "Hey, what's up?\n\n- You"
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
print("establish connection successful")
server.ehlo()
print("identification successful")
server.login(gmail_user, gmail_password)
print("login successful")
server.sendmail(sent_from, to, email_text)
print("send mail successful")
server.close()
print('Email sent!')
except:
print('Something went wrong...')
Does anyone know how I can fill them up through this script?
For the email subject - there is a specific format to the input arg you provide to server.sendmail that should work. Could you try:
subject = 'This is the email subject'
text = 'This is the email body'
message = "Subject: {}\n\n{}".format(subject, text)
server.sendmail(sender, recipient, message)
If you try to open the source of an email you will see something like this:
Received: from ************.net ([***.**.2.17]) by
*****.****.net ([**.***.224.162]) with mapi id **.03.****.***;
Mon, 22 May 2017 09:14:59 +0200
From: *FROMEMAIL* <******#***.com>
To: *TOEMAIL* <********#***.com>
CC: *CCEMAIL* <********#*****.com>
Subject: E-mail - 150633**0686_****.pdf
...
That is the header of the email, so if you try something like this:
import smtplib
gmail_user = 'dummy#gmail.com'
gmail_password = 'password'
sent_from = 'dummy#gmail.com'
to = ['receiver#gmail.com']
subject = 'OMG Super Important Message'
body = "Hey, what's up?\n\n- You"
cc = "****#***.com"
bcc = "******#*****.com"
email_text = """\
From: %s
To: %s
CC: %s
BCC: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), cc, bcc,subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
print("establish connection successful")
server.ehlo()
print("identification successful")
server.login(gmail_user, gmail_password)
print("login successful")
server.sendmail(sent_from, to, email_text)
print("send mail successful")
server.close()
print('Email sent!')
except:
print('Something went wrong...')
I think it will work
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"
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())