I want to get a log when I email to the wrong email address.
so, I wrote this command.
mailserver = mymailserver
to_email = emailaddress
from_email = fromaddress
subject = SBJECT
original_message = TEXT
message = MESSAGE
server = smtplib.SMTP(mailserver)
debug = server.set_debuglevel(1)
server.sendmail(from_mail,to_mail, message)
server.quit()
print(debug)
I just want to know connection status log.
wchich code should I edit?
I tried this scripts, but it does not work well.
server = smtplib.SMTP(mailserver)
mail_response = server.sendmail(from_mail,to_mail, message)
server.quit()
print(mail_response)
Thank you for helping me.
Try This and read the docs. Hope it will help you
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
# Or simply skip this part
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = f'The contents of {textfile}'
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
Related
I am a beginner programmer and I am trying to write a program that automatically sends personalized emails to a list of receivers in a csv file with a pdf attachment.
My current code sends personalized emails but I don't know how to add an attachment. Also, I think it's best practice to write the program in a function but I don't know how to do that either.
It would be greatly appreciated if anyone could help me out. Also, I want to keep it as simple as possible so that I still understand what every line of code does.
import os
import smtplib, ssl
import csv
# Sender credentials (from environment variables)
email_address = os.environ.get("email_user")
email_pass = os.environ.get("email_app_pass")
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(email_address, email_pass) # Log into sender email account
# Email information
subject = "Testing Python Automation"
body = """ Hi {name},\n\n This email was entirely generated in Python. So cool!
"""
msg = f"Subject: {subject}\n\n{body}"
with open("contacts_test.csv") as file:
reader = csv.reader(file)
next(reader) # Skip header row
for name, email in reader:
server.sendmail(email_address, email, msg.format(name=name))
file.close()
server.quit()
This will only work using gmail and make sure you have manually set up
special permissions on your gmail account for the program to be able to send email on behalf of you. The process is described here.
You can use other email address services for that you need to change the smtp server address and the smtp port number in line 32 accordingly and take care of any other additional steps required.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
body = """
Hi {name},\n\n This email was entirely generated in Python. So cool!
""".format(name="Name")
# details
sender = 'example1#gmail.com' # my email
password = '&*password.$' # my email's password
receiver = 'example2#gmail.com' # receiver's email
msg = MIMEMultipart()
msg['To'] = receiver
msg['From'] = sender
msg['Subject'] = 'Testing Python Automation'
msg.attach(MIMEText(body, 'plain'))
pdfname = "mypdf.pdf" # pdf file name
binary_pdf = open(pdfname, 'rb')
payload = MIMEBase('application', 'octate-stream', Name=pdfname)
payload.set_payload((binary_pdf).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=pdfname)
msg.attach(payload)
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender, password)
text = msg.as_string()
session.sendmail(sender, receiver, text)
session.quit()
print('[#] Mail Sent!')
I have put together a function send_email [1] to send emails with support for plain-text and html messages. It works well, but I have an issue I don't quite know how to debug. My system has sendmail as its MTA.
The function is called in a for loop, as follows:
for data in data_set:
subject, message = process(data) # Irrelevant stuff
send_email(subject, message, "fixed#email.address")
In the debug output of smtplib [1] I see that all calls to send_email completed successfully. The weird behavior is:
If the message is "short" (I tested with a single line), all sent messages actually arrive to fixed#email.address
If the message is "not short" (that is, the multiple lines I generate with the real process_data function), only the first email does arrive, while the others don't, even though the debug output of smtplib in [1] reports success for each and all of the emails.
If the message is equally "not short" but the destination address is different for each message, then all messages arrive to their intended destinations.
For the latter case, the for loop would look like:
addresses = ["fixed#email.address", "fixed.2#email.address", ...]
for data, addr in zip(data_set, addresses):
subject, message = process(data) # Irrelevant stuff
send_email(subject, message, addr)
The intended behavior is of course different addresses for different data, but I'm concerned that not understanding why this happens might bite me in an unexpected way later on.
[1] My send mail function:
import smtplib
import socket
import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email (subject, message, to, reply_to='', cc='', html_message=''):
COMMASPACE = ", "
user, host = get_user_and_host_names()
sender = '%s#%s' % (user, host)
receivers = make_address_list(to)
copies = make_address_list(cc)
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = COMMASPACE.join(receivers)
if reply_to:
msg.add_header('Reply-to', reply_to)
if len(copies):
msg.add_header('CC', COMMASPACE.join(copies))
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
if message:
msg.attach( MIMEText(message, 'plain'))
if html_message:
msg.attach( MIMEText(html_message, 'html'))
smtpObj = smtplib.SMTP('localhost')
smtpObj.set_debuglevel(1)
smtpObj.sendmail(sender, receivers, msg.as_string())
smtpObj.quit()
print "\nSuccessfully sent email to:", COMMASPACE.join(receivers)
def get_user_and_host_names():
user = getpass.getuser()
host = socket.gethostname()
return user, host
def make_address_list (addresses):
if isinstance(addresses, str):
receivers = addresses.replace(' ','').split(',')
elif isinstance(addresses, list):
receivers = addresses
return receivers
A working solution I had for sending email:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import smtplib
class EMail(object):
""" Class defines method to send email
"""
def __init__(self, mailFrom, server, usrname, password, files, debug=False):
self.debug = debug
self.mailFrom = mailFrom
self.smtpserver = server
self.EMAIL_PORT = 587
self.usrname = usrname
self.password = password
def sendMessage(self, subject, msgContent, files, mailto):
""" Send the email message
Args:
subject(string): subject for the email
msgContent(string): email message Content
files(List): list of files to be attached
mailto(string): email address to be sent to
"""
msg = self.prepareMail(subject, msgContent, files, mailto)
# connect to server and send email
server=smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT)
server.ehlo()
# use encrypted SSL mode
server.starttls()
# to make starttls work
server.ehlo()
server.login(self.usrname, self.password)
server.set_debuglevel(self.debug)
try:
failed = server.sendmail(self.mailFrom, mailto, msg.as_string())
except Exception as er:
print er
finally:
server.quit()
def prepareMail(self, subject, msgHTML, attachments, mailto):
""" Prepare the email to send
Args:
subject(string): subject of the email.
msgHTML(string): HTML formatted email message Content.
attachments(List): list of file paths to be attached with email.
"""
msg = MIMEMultipart()
msg['From'] = self.mailFrom
msg['To'] = mailto
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
#the Body message
msg.attach(MIMEText(msgHTML, 'html'))
msg.attach(MIMEText("Add signature here"))
if attachments:
for phile in attachments:
# we could check for MIMETypes here
part = MIMEBase('application',"octet-stream")
part.set_payload(open(phile, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(phile))
msg.attach(part)
return msg
I hope this helps.
My Working solution to format your list in this manner (after many hours of experiment):
["firstemail#mail.com", "secondmail#mail.com", "thirdmail#email.com"]
I used:
to_address = list(str(self.to_address_list).split(","))
to convert my QString into string then into list with splitting with a ","
In my case COMMASPACE was not working, because on splitting a space was already added by default.
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()
I am looking for a quick example on how to send Gmail emails with multiple CC:'s. Could anyone suggest an example snippet?
I've rustled up a bit of code for you that shows how to connect to an SMTP server, construct an email (with a couple of addresses in the Cc field), and send it. Hopefully the liberal application of comments will make it easy to understand.
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
## The SMTP server details
smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"
## The email details
from_address = "address1#domain.com"
to_address = "address2#domain.com"
cc_addresses = ["address3#domain.com", "address4#domain.com"]
msg_subject = "This is the subject of the email"
msg_body = """
This is some text for the email body.
"""
## Now we make the email
msg = MIMEText(msg_body) # Create a Message object with the body text
# Now add the headers
msg['Subject'] = msg_subject
msg['From'] = from_address
msg['To'] = to_address
msg['Cc'] = ', '.join(cc_addresses) # Comma separate multiple addresses
## Now we can connect to the server and send the email
s = SMTP_SSL(smtp_server, smtp_port) # Set up the connection to the SMTP server
try:
s.set_debuglevel(True) # It's nice to see what's going on
s.ehlo() # identify ourselves, prompting server for supported features
# If we can encrypt this session, do it
if s.has_extn('STARTTLS'):
s.starttls()
s.ehlo() # re-identify ourselves over TLS connection
s.login(smtp_username, smtp_password) # Login
# Send the email. Note we have to give sendmail() the message as a string
# rather than a message object, so we need to do msg.as_string()
s.sendmail(from_address, to_address, msg.as_string())
finally:
s.quit() # Close the connection
Here's the code above on pastie.org for easier reading
Regarding the specific question of multiple Cc addresses, as you can see in the code above, you need to use a comma separated string of email addresses, rather than a list.
If you want names as well as addresses you might as well use the email.utils.formataddr() function to help get them into the right format:
>>> from email.utils import formataddr
>>> addresses = [("John Doe", "john#domain.com"), ("Jane Doe", "jane#domain.com")]
>>> ', '.join([formataddr(address) for address in addresses])
'John Doe <john#domain.com>, Jane Doe <jane#domain.com>'
Hope this helps, let me know if you have any problems.
If you can use a library, I highly suggest http://libgmail.sourceforge.net/, I have used briefly in the past, and it is very easy to use. You must enable IMAP/POP3 in your gmail account in order to use this.
As for a code snippet (I haven't had a chance to try this, I will edit this if I can):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
#EDIT THE NEXT TWO LINES
gmail_user = "your_email#gmail.com"
gmail_pwd = "your_password"
def mail(to, subject, text, attach, cc):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
#THIS IS WHERE YOU PUT IN THE CC EMAILS
msg['Cc'] = cc
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
mail("some.person#some.address.com",
"Hello from python!",
"This is a email sent with python")
For the snippet I modified this