I try to send email with amazon SES API docs below, and python return the code 250 meaing OK but my email got a failure message. Could anyone kindly tell me what maybe the problem? thank you
python:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# https://us-east-2.console.aws.amazon.com/sesv2/home?region=us-east-2#/account
# https://console.aws.amazon.com/iam/home?#/s=SESHomeV4/us-east-2
mail_host = "email-smtp.us-east-2.amazonaws.com"
mail_user = "AKI....T7H"
mail_pass = "BHJ.....iS/x"
sender = 'thelou1s#...com'
receivers = 'thelou1s#...com'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receivers
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
try:
print("try smtplib.SMTP")
smtp = smtplib.SMTP(mail_host, 587)
smtp.set_debuglevel(True)
print("try connect")
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
# smtpObj.connect(mail_host, 465)
print("try login")
smtp.login(mail_user, mail_pass)
print("try sendmail: " + msg.as_string())
smtp.sendmail(sender, receivers, msg.as_string())
print("Send Success")
smtp.close()
except smtplib.SMTPException:
print("Send Error")
log (Is retcode 250 means success in code side or user side?):
reply: retcode (250); Msg: b'Ok 010f017d8f0f1703-d018f2a9-833e-428e-9010-5e45818e51e4-000000'
data: (250, b'Ok 010f017d8f0f1703-d018f2a9-833e-428e-9010-5e45818e51e4-000000')
Send Success
emails from amazon:
Delivery Status Notification (Failure)
An error occurred while trying to deliver the mail to the following recipients:
thelou1s#...com
here is the email
Just validate your email in amazon console
Related
I am attempting to send an email, but I run into this error:
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor d2sm13023190qkl.98 - gsmtp')
In the web URL i dont see anything super useful, would anyone have any tips? For SO purposes I left the email account passwords as test versus sharing my person info..
import smtplib
import ssl
# User configuration
sender_email = 'test#gmail.com'
receiver_email = 'test#gmail.com'
password = 'test'
# Email text
email_body = '''
This is a test email sent by Python. Isn't that cool?
'''
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, email_body)
print('Email sent!')
print('Closing the server...')
server.quit()
I tried my best... I think this should work!
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email = "test#gmail.com" # the email where you sent the email
password = "yourPassword"
send_to_email = "yourEmail#gmail.com" # for whom
subject = "Gmail"
message = "This is a test email sent by Python. Isn't that cool?!"
msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to_email
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_email, text)
server.quit()
You must allow the "Less secure apps" in Google configurations.
Here is the link of another thread about it : Link
I recently wrote a script that sent me an email if a website I wanted to monitor had changed using smtplib. The program works, and I get the email but when I look at the sent email (as I am sending myself the email from the same account), it says that there is no recipient or 'To:' address, only a Bcc with the address I want the email to be sent to. Is this a feature of smtplib -- that it doesn't actually add a 'To:' address, only Bcc addresses? code is as follows:
if (old_source != new_source):
# now we create a mesasge to send via email
fromAddr = "example#gmail.com"
toAddr = "example#gmail.com"
msg = ""
# smtp login
username = "example#gmail.com"
pswd = "password"
# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()
Updating your code as follows will do the trick:
if (old_source != new_source):
# now we create a mesasge to send via email
fromAddr = "example#gmail.com"
toAddr = "example#gmail.com"
msg = ""
# smtp login
username = "example#gmail.com"
pswd = "password"
# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
header = 'To:' + toAddr + '\n' + 'From: ' + fromAddr + '\n' + 'Subject:testing \n'
msg = header + msg
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()
Try manually adding any headers to your message, separated from the body by a blank line e.g.:
...
msg="""From: sender#domain.org
To: recipient#otherdomain.org
Subject: Test mail
Mail body, ..."""
...
Try this, seems to work for me.
#!/usr/bin/python
#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
sender = 'example#gmail.com'
receivers = ['example#gmail.com']
msg = MIMEMultipart()
msg['From'] = 'example#gmail.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))
ServerConnect = False
try:
smtp_server = SMTP('smtp.gmail.com','465')
smtp_server.login('######gmail.com', '############')
ServerConnect = True
except SMTPHeloError as e:
print "Server did not reply"
except SMTPAuthenticationError as e:
print "Incorrect username/password combination"
except SMTPException as e:
print "Authentication failed"
if ServerConnect == True:
try:
smtp_server.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except SMTPException as e:
print "Error: unable to send email", e
finally:
smtp_server.close()
Just throwing it out there: please try yagmail. Disclaimer: I'm the maintainer, but I feel like it can help everyone out!
It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
Which will also set the headers :)
You'll have to install yagmail first with either:
pip install yagmail # python 2
pip3 install yagmail # python 3
Once you will want to also embed html/images or add attachments, you'll really love the package!
It will also make it a lot safer by preventing you from having to have your password in the code.
I have been trying to send a mail from python to Outlook. The body does not appear in the mail. The mail gets send, with the subject. The body is blank. What could be the issue?
Here is my code:
import smtplib
username = "neooooo#example.com"
password = "#death123"
print("Logged in ")
vtext = "nihjdoiwjadv#example.com"
message = "this is the message to be sent"
msg = """From: %s
To: %s
Subject: Hi
Body:%s""" % (username, vtext, message)
print("Connecting to server")
server = smtplib.SMTP('smtp.office365.com',587)
server.starttls()
server.login(username,password)
server.sendmail(username, vtext, msg)
server.quit()
print("Done")
The body is not part of the headers, especially there is no header called Body. The body of a mail comes after the headers, separated by a blank line.
Try this code. It works for me.
import smtplib,getpass,os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
os.system('clear')
msg=MIMEMultipart()
print "---------Python Mail Sender--------\n---------ONLY GMAIL Sender---------"
frm=raw_input("From : ")
to=raw_input("To : ")
msg['From']=frm
msg['To']=to
msg['Subject']=raw_input("Enter Subnject of mail : ")
text=raw_input("Enter text to send in mail : ")
msg.attach(MIMEText(text))
try :
mailserver=smtplib.SMTP("smtp.gmail.com",587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login(frm,getpass.getpass("Enter you password(Will not be visible as you Enter) : "))
mailserver.sendmail(frm,to,msg.as_string())
except Exception,e:
print "ERROR : ",e
finally:
mailserver.quit()
I am developing an application using python where I need to send a file through mail. I wrote a program to send the mail but dont know there's something wrong. The code is posted below. Please any one help me with this smtp library. Is there's anything i m missing? And also can someone please tell me what will be the host in smtp! I am using smtp.gmail.com.
Also can any one tell me how can i email a file (.csv file). Thanks for the help!
#!/usr/bin/python
import smtplib
sender = 'someone#yahoo.com'
receivers = ['someone#yahoo.com']
message = """From: From Person <someone#yahoo.com>
To: To Person <someone#yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
You aren't logging in. There are also a couple reasons you might not make it through including blocking by your ISP, gmail bouncing you if it can't get a reverse DNS on you, etc.
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587) # or 465
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(account, password)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
I just noticed your request to be able to attach a file. That changes things since now you need to deal with encoding. Still not that tough to follow though I don't think.
import os
import email
import email.encoders
import email.mime.text
import smtplib
# message/email details
my_email = 'myemail#gmail.com'
my_passw = 'asecret!'
recipients = ['jack#gmail.com', 'jill#gmail.com']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'
# build the message
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email.Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email.MIMEText.MIMEText(message))
# build the attachment
att = email.MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)
# send the message
srv = smtplib.SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())
I am successfully able to send email using the smtplib module. But when the emial is sent, it does not include the subject in the email sent.
import smtplib
SERVER = <localhost>
FROM = <from-address>
TO = [<to-addres>]
SUBJECT = "Hello!"
message = "Test"
TEXT = "This message was sent with Python's smtplib."
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
How should I write "server.sendmail" to include the SUBJECT as well in the email sent.
If I use, server.sendmail(FROM, TO, message, SUBJECT), it gives error about "smtplib.SMTPSenderRefused"
Attach it as a header:
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
and then:
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Also consider using standard Python module email - it will help you a lot while composing emails. Using it would look like this:
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = TO
msg.set_content(TEXT)
server.send_message(msg)
This will work with Gmail and Python 3.6+ using the new "EmailMessage" object:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content('This is my message')
msg['Subject'] = 'Subject'
msg['From'] = "me#gmail.com"
msg['To'] = "you#gmail.com"
# Send the message via our own SMTP server.
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("me#gmail.com", "password")
server.send_message(msg)
server.quit()
try this:
import smtplib
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = 'sender_address'
msg['To'] = 'reciver_address'
msg['Subject'] = 'your_subject'
server = smtplib.SMTP('localhost')
server.sendmail('from_addr','to_addr',msg.as_string())
You should probably modify your code to something like this:
from smtplib import SMTP as smtp
from email.mime.text import MIMEText as text
s = smtp(server)
s.login(<mail-user>, <mail-pass>)
m = text(message)
m['Subject'] = 'Hello!'
m['From'] = <from-address>
m['To'] = <to-address>
s.sendmail(<from-address>, <to-address>, m.as_string())
Obviously, the <> variables need to be actual string values, or valid variables, I just filled them in as place holders. This works for me when sending messages with subjects.
See the note at the bottom of smtplib's documentation:
In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.
Here's the link to the examples section of email's documentation, which indeed shows the creation of a message with a subject line. https://docs.python.org/3/library/email.examples.html
It appears that smtplib doesn't support subject addition directly and expects the msg to already be formatted with a subject, etc. That's where the email module comes in.
import smtplib
# creates SMTP session
List item
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("login mail ID", "password")
# message to be sent
SUBJECT = "Subject"
TEXT = "Message body"
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
# sending the mail
s.sendmail("from", "to", message)
# terminating the session
s.quit()
I think you have to include it in the message:
import smtplib
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
code from: http://www.tutorialspoint.com/python/python_sending_email.htm
In case of wrapping it in a function, this should work as a template.
def send_email(login, password, destinations, subject, message):
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(login, password)
message = 'Subject: {}\n\n{}'.format(subject, message)
for destination in destinations:
print("Sending email to:", destination)
server.sendmail(login, destinations, message)
server.quit()
try this out :
from = "myemail#site.com"
to= "someemail#site.com"
subject = "Hello there!"
body = "Have a good day."
message = "Subject:" + subject + "\n" + body
server.sendmail(from, , message)
server.quit()