Python SMTP what is wrong with the syntax? - python

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"

Related

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.

How to insert var content inside message body of sendmail function

I have the next function:
hostname = os.uname()[1]
def sendmail(sender, receiver, content, user=None, password=None, hostname='localhost', port=25,ssl=False):
smt_server = 'localhost'
port = '25'
sender = 'jenkins#jenkins.com'
receiver = 'test#test.es'
content = "I need to show hostname here" , hostname , "Done."
msg = MIMEText(content)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Simple app script'
try:
s = smtplib.SMTP('localhost', port )
s.sendmail('jenkins#jenkins.com', 'test#test.es', content)
s.quit()
print "Succesfully sent email"
except SMTPException:
print "Error: fail to send email"
Actual result:
AttributeError: 'tuple' object has no attribute 'encode'
Expected result:
The body message of the mail have to be:
I need to show hostname here MyHostname Done.
I'm not sure if i'm using the rigth way, could you help me?
Thanks
You can add strings:
content = "I need to show hostname here" + hostname + "Done."
Try this to make content one string.
content = "I need to show hostname here " + hostname + " Done."

Populate other email fields like Subject in Python mail function

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

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 email sending script gmail

I am making a simple script for send mail through gmail account in python 2.7.5.. Before send mail i wanna check that whether user successfully login through gmail smtp or not... Here is my code:
#!/usr/bin/python
import smtplib
user = raw_input("Enter Your email address: ")
password= raw_input("Enter your email password: ")
receipt = raw_input("Enter Receipt email address: ")
subject = raw_input ("Subject: ")
msg = raw_input("Message: ")
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (user, ", ".join(receipt), subject, msg)
smtp_host = 'smtp.gmail.com'
smtp_port = 587
session = smtplib.SMTP()
session.connect(smtp_host, smtp_port)
session.ehlo()
session.starttls()
session.ehlo
print "Connecting to the server....."
try:
session.login(user, password)
if (session.verify(True)):
print "Connected to the server. Now sending mail...."
session.sendmail(user, receipt, message)
session.quit()
print "Mail have been sent successfully.....!"
except smtplib.SMTPAuthenticationError:
print "Can not connected to the Server...!"
print "Simple mail Test"
But when i run it, then it will give "Can not Connected to the Server". can any body help me what i am doing wrong?
You just forgot a couple of things. The receipt have to be a list, and the verify method take the user email as argument. Here's the code with some improvements:
#!/usr/bin/python
import smtplib
receipt,cc_list=[],[]
user = raw_input("Enter Your email address: ")
password= raw_input("Enter your email password: ")
receipt.append(raw_input("Enter Receipt email address: "))
subject = raw_input ("Subject: ")
message = raw_input("Message: ")
header = 'From: %s\n' % user
header += 'To: %s\n' % ','.join(receipt)
header += 'Cc: %s\n' % ','.join(cc_list)
header += 'Subject: %s\n\n' % subject
message = header + message
smtp_host = 'smtp.gmail.com'
smtp_port = 587
session = smtplib.SMTP()
session.connect(smtp_host, smtp_port)
session.ehlo()
session.starttls()
session.ehlo
print "Connecting to the server....."
try:
session.login(user, password)
if (session.verify(user)):
print "Connected to the server. Now sending mail...."
session.sendmail(user, receipt, message)
session.quit()
print "Mail have been sent successfully.....!"
except smtplib.SMTPAuthenticationError:
print "Can not connected to the Server...!"
print "Simple mail Test"

Categories