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"
Related
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.
I'm a very new Python coder so please don't go too harsh on me, thanks.
I'm trying to make an emailer using smtplib and I'm having trouble with handing the users credentials to Google.
Full code:
mailcheck = input("This mailer is only for gmail, want to continue? (yes or no)")
# GMAIL SMTP INFORMATION
if mailcheck == "yes" or mailcheck == "Yes" or mailcheck == "y":
smtp_server = 'smtp.gmail.com'
port = 587
set_server = "gmail"
else:
print("Hey, sorry this program is only for Gmail")
#USER CREDENTIALS + RECEIVER
username = input("Google Email?")
password = input("Password?")
receiver = input("Who to send it to?")
subject = input("Subject of the email?")
econtents = input("What to put in the email?")
amount = input("Amount of emails to send?")
credentials = username + password
global d1
global d2
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls()
server.login(username, password)
print("Sending" + amount, "to", receiver)
for i in range(1, int(amount) + 1):
message = "From" + credentials[0] + '\nSubject' + subject + '\n' + econtents
time.sleep(random.uniform(d1, d2))
server.sendmail(credentials[0], receiver, message)
print("\nEmail Sent!")
else:
print("Finished sending emails")
except smtplib.SMTPRecipientsRefused:
print("Recipient refused. Invalid email address?")
except smtplib.SMTPAuthenticationError:
print("Unable to authenticate with server. Ensure the details are correct.")
except smtplib.SMTPServerDisconnected:
print("Server disconnected for an unknown reason.")
except smtplib.SMTPConnectError:
print("Unable to connect to server.")
The error :
Unable to authenticate with server. Ensure the details are correct.
This means it went wrong with the login process. It should be going wrong somewhere in this part:
#USER CREDENTIALS + RECEIVER
username = input("Google Email?")
password = input("Password?")
receiver = input("Who to send it to?")
subject = input("Subject of the email?")
econtents = input("What to put in the email?")
amount = input("Amount of emails to send?")
credentials = username + password
global d1
global d2
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls()
server.login(username, password)
print("Sending" + amount, "to", receiver)
for i in range(1, int(amount) + 1):
message = "From" + credentials[0] + '\nSubject' + subject + '\n' + econtents
time.sleep(random.uniform(d1, d2))
server.sendmail(credentials[0], receiver, message)
print("\nEmail Sent!")
I think it's because of the credentials = username + password which doesn't work, but I have no idea how I'd fix it.
If anyone knows what I'd have to change to fix this that'd be great!
Instead of adding those two strings, you're meaning to put them in an array. In Python, that's either
credentials = [username, password]
or
credentials = list(username, password)
But that doesn't seem to be your issue. Your issue is related to the login() function as you get the SMTPAuthenticationError exception. The smtplib documentation says that after running .starttls(), you should run .ehlo() again. Try to run that before logging in. Additionally, you could try to generate an SSL instance on port 465.
(Ctrl+F for .starttls())
https://docs.python.org/2/library/smtplib.html
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 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)
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"