Sending/Receiving E-mail with Python smtpd module - python

I'm trying to make a simple smtp server using the Python smtpd module. I can receive an e-mail and print it out. I try to send an e-mail back to the person who sent me the e-mail with a hello world message and I end up with an infinite loop. I try to use my own server to send the e-mail and it just interprets it as another e-mail that's been received.
How can I use this to both send and receive e-mail?
import smtplib, smtpd
import asyncore
import email.utils
from email.mime.text import MIMEText
import threading
class SMTPReceiver(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print 'Receiving message from:', peer
print 'Message addressed from:', mailfrom
print 'Message addressed to :', rcpttos
print 'Message length :', len(data)
print data
def send_response():
msg = MIMEText('Hello world!')
msg['To'] = email.utils.formataddr(('Recipient', mailfrom))
msg['From'] = email.utils.formataddr(('Author', 'jsternberg#example.org'))
msg['Subject'] = ''
print 'Connecting to mail server'
server = smtplib.SMTP()
server.set_debuglevel(1)
server.connect()
print 'Attempting to send message'
try:
server.sendmail('jsternberg#example.org', [mailfrom], msg.as_string())
except Exception, ex:
print 'Could not send mail', ex
finally:
server.quit()
print 'Finished sending message'
threading.Thread(target=send_response).start()
return
def main():
server = SMTPReceiver(('', 25), None)
asyncore.loop()
if __name__ == '__main__':
main()
Note: Not using a real e-mail address in the example.
Note 2: Not using this as a mail server. Just want to send/receive simple e-mails for a simple service.

You're not supposed to send the message to yourself...
Perform a MX lookup and send the message to the appropriate SMTP server.

Related

Sending email using smtplib without logging in [duplicate]

I want to send an email without login to server in Python. I am using Python 3.6.
I tried some code but received an error. Here is my Code :
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer)
server.set_debuglevel(1)
server.sendmail(fromAddr, toAddr, text)
server.quit()
I expect the mail should be sent without asking user id and password but getting an error :
"smtplib.SMTPSenderRefused: (530, b'5.7.1 Client was not authenticated', 'from#Address.com')"
I am using like this. It's work to me in my private SMTP server.
import smtplib
host = "server.smtp.com"
server = smtplib.SMTP(host)
FROM = "testpython#test.com"
TO = "bla#test.com"
MSG = "Subject: Test email python\n\nBody of your message!"
server.sendmail(FROM, TO, MSG)
server.quit()
print ("Email Send")
import win32com.client as win32
outlook=win32.Dispatch('outlook.application')
mail=outlook.CreateItem(0)
mail.To='To address'
mail.Subject='Message subject'
mail.Body='Message body'
mail.HTMLBody='<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment="Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
The code below worked for me.
First, I opened/enabled Port 25 through Network Team and used it in the program.
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer,25)
server.ehlo()
server.starttls()
server.sendmail(fromAddr, toAddr, text)
server.quit()
First, you have to have a SMTP server to send an email. When you don't have one, usually outlook's server is used. But outlook only accepts authenticated users, so if you don't want to login into the server, you have to pick a server that doesn't need authentication.
A second approach is to setup an internal SMTP server. After you setup the internal SMTP server, you can use the "localhost" as the server to send the email. Like this:
import smtplib
receiver = 'someonesEmail#hisDomain.com'
sender = 'yourEmail#yourDomain.com'
smtp = smtplib.SMTP('localhost')
subject = 'test'
body = 'testing plain text message'
msg = 'subject: ' + subject + ' \n\n' + body
smtp.sendmail('sender', receiver, msg)

Open relay python

#!/usr/bin/python
import smtplib
message = """From: Test <test#fromdomain.com>
To: test<test#todomain.com>
Subject: SMTP test
This is test
"""
try:
smtpObj = smtplib.LMTP('exhange.intranet',25)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Hello basiclly im testing open relay server and here is question is there other method to send mail without any authetication than LMTP ?How i can implement this with SMTP which paramter is that ?
Sending a mail with only smtp is getting blocked on exhange easyli, there must be included NOT authetication information for exhange to pass it through.
To use SMTP without authentication, use code like the following:
smtpObj = smtplib.SMTP('exhange.intranet',25)
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()

Send anonymous mail from local machine

I was using Python for sending an email using an external SMTP server. In the code below, I tried using smtp.gmail.com to send an email from a gmail id to some other id. I was able to produce the output with the code below.
import smtplib
from email.MIMEText import MIMEText
import socket
socket.setdefaulttimeout(None)
HOST = "smtp.gmail.com"
PORT = "587"
sender= "somemail#gmail.com"
password = "pass"
receiver= "receiver#somedomain.com"
msg = MIMEText("Hello World")
msg['Subject'] = 'Subject - Hello World'
msg['From'] = sender
msg['To'] = receiver
server = smtplib.SMTP()
server.connect(HOST, PORT)
server.starttls()
server.login(sender,password)
server.sendmail(sender,receiver, msg.as_string())
server.close()
But I have to do the same without the help of an external SMTP server. How can do the same with Python?
Please help.
The best way to achieve this is understand the Fake SMTP code it uses the great smtpd module.
#!/usr/bin/env python
"""A noddy fake smtp server."""
import smtpd
import asyncore
class FakeSMTPServer(smtpd.SMTPServer):
"""A Fake smtp server"""
def __init__(*args, **kwargs):
print "Running fake smtp server on port 25"
smtpd.SMTPServer.__init__(*args, **kwargs)
def process_message(*args, **kwargs):
pass
if __name__ == "__main__":
smtp_server = FakeSMTPServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
smtp_server.close()
To use this, save the above as fake_stmp.py and:
chmod +x fake_smtp.py
sudo ./fake_smtp.py
If you really want to go into more details, then I suggest that you understand the source code of that module.
If that doesn't work try the smtplib:
import smtplib
SERVER = "localhost"
FROM = "sender#example.com"
TO = ["user#example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Most likely, you may already have an SMTP server running on the host that you are working on. If you do ls -l /usr/sbin/sendmail does it show that an executable file (or symlink to another file) exists at this location? If so, then you may be able to use this to send outgoing mail. Try /usr/sbin/sendmail recipient#recipientdomain.com < /path/to/file.txt to send the message contained in /path/to/file.txt to recipient#recipientdomain.com (/path/to/file.txt should be an RFC-compliant email message). If that works, then you can use /usr/sbin/sendmail to send mail from your python script - either by opening a handle to /usr/sbin/sendmail and writing the message to it, or simply by executing the above command from your python script by way of a system call.

Cannot send an email with python smtp

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())

Python: "subject" not shown when sending email using smtplib module

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()

Categories