Populate other email fields like Subject in Python mail function - python

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

Related

How to take a screenshot when except happens and send it in a email? (Python)

I want to take a screenshot using python/selenium when an except happens and send it through an email? How do I do this? I don't want to save it, but I don't mind saving it to a folder but I want to send an email with where the error happened. All examples so far I've seen seem to be saving it to a folder. My code below.
def myfunction(self):
try:
#some code
except NoSuchElementException:
print("error appeared")
#take screenshot here
subject = '')
message = (f"""Here is the screeenshot of the error """)
self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, self.errorReportemail, subject, message)
for mail in self.ccBots:
self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, mail, subject, message)
def sendEmailBOTS(self, email, password, send_to, subject, message):
print("Sending email to", send_to)
logging.info("Sending email to")
msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to
msg["Subject"] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to, text)
server.quit()
You can try to take a screen shot like this :
myfunction(self):
try:
# some code
except NoSuchElementException:
print("error appeared")
# take screenshot here
driver.save_screenshot('file name here')
def somefunction(self):
imagepath = os.path.join(root, 'Errorimages\\ERROR')
image_screenshot = imagepath + ".png"
self.driver.save_screenshot(image_screenshot)
subject = '')
message = (f"""Here is the screeenshot of the error """)
self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, self.errorReportemail, subject, message)
for mail in self.ccBots:
self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, mail, subject, message)
def filefunction(self):
def sendEmailBOTS(self, email, password, send_to, subject, message):
print("Sending email to", send_to)
logging.info("Sending email to")
msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to
msg["Subject"] = subject
msg.attach(MIMEText(message, 'plain'))
filename = "ERROR.png"
locationImages = os.path.join(root, 'Errorimages\\ERROR.png')
attachment = open(locationImages, "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.gmail.com", 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to, text)
server.quit()
This is what I came up with. Its not perfect but it takes the screenshot ,saves it in a folder and then the email sends that picture.

Weird display of 'From' field in smtp email sent in python

I am getting weird display of From field in smtp email.The display is like;
from: test#gmail.com To: test#gmail.com, Subject: Message test#gmail.com
to:
to field is blank but the another 'to' recipient, ie test1#gmail.com received the email successfully.
Below is my code.
import smtplib
def SendEmailScenario1():
gmail_user = "test#gmail.com"
gmail_password = '******'
sent_from = gmail_user
to = ["test1#gmail.com"]
subject = 'Message'
body = "Hi There! Done1"
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('Email sent!')
except:
print ('Something went wrong...')
def SendEmailScenario2():
gmail_user = "test#gmail.com"
gmail_password = '******'
sent_from = gmail_user
to = ["test1#gmail.com"]
subject = 'Message'
body = "Hi There! Done 2"
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('Email sent!')
except:
print ('Something went wrong...')
SendEmailScenario1()
SendEmailScenario2()
How to bring it to normal display without using MIMEText, MIMEMultipart
RFC822 specifies that a header should terminate with '\r\n':
field = field-name ":" [ field-body ] CRLF
Furthermore, the headers should be separated from the body by an empty '\r\n':
[The body] is separated from the headers by a null line (i.e., a
line with nothing preceding the CRLF)
So the message should be constructed like this:
headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
email_text = headers + body
See also the example in the smtplib docs.

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)

In python's smtplib why isn't the subject or From field set?

can anyone see why the following code sends emails successfully but it shows up as being from the email address of the sender instead of the name of the sender in the recipients inbox, and the subject shows up as "No Subject" in their inbox. Thanks in advance.
def send_email(destination, subject, message):
from_who = "My Name"
to_send = """\From: %s\nTo: %s\nSubject: %s\n\n%s""" % (from_who, destination, subject, message)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(my_email_addr, my_pwrd)
server.sendmail(from_who, destination, message)
server.close()
except:
print "failed"
If you want to use SMTP in python, you need to send the data as a dictionary.
from email.parser import Parser
# This will parse out your to-, from-, and subject fields automatically
headers = Parser().parsestr(to_send)
# This will take care of the to- and from-fields for you
server.send_message(headers)
test.py
from email.parser import Parser
from_whom = "hello#example.com"
destination = "world#example.com"
subject = "Foobar!"
message = "Bar bar binks"
to_send = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (from_whom, destination, subject, message)
print(to_send)
headers = Parser().parsestr(to_send)
print(headers["To"]) # world#example.com
print(headers["From"]) # hello#example.com
print(headers["Subject"]) # Foobar!
EDIT
Alternatively, you could do this:
to_send = string.join((
"From: %s" % from_whom,
"To: %s" % destination,
"Subject: %s" % subject,
"",
message
), "\r\n")
# ...
server.sendmail(from_whom, [destination], to_send)
# ...
I think the other way is cleaner, but this is up to you.

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