This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I try to send an email via python.
According to my script the sending was successfull.
import smtplib
sender = 'from#fromdomain.com'
receivers = ['my#emailadress.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('127.0.0.1', 1025)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
But when I check my emails, I got no new mails. :(
Where is the problem? Where is my sent email?
Edit:
My smtp test server are:
import smtpd
import asyncore
class CustomSMTPServer(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)
return
server = CustomSMTPServer(('127.0.0.1', 1025), None)
print "Started...."
asyncore.loop()
And my smtp Server says:
Receiving message from: ('127.0.0.1', 65071)
Message addressed from: from#fromdomain.com
Message addressed to : ['my#emailadress.com']
Message length : 129
process_message() does nothing but output its input data. So it displays data about the mail it got, but it doesn't forward this mail to your real inbox, but drops the data.
So it is normal that you don't get the mail.
Related
This question already has an answer here:
aiosmtpd - python smtp server
(1 answer)
Closed 3 months ago.
I had "successfully" made an SMTP server. The code works fine connecting to SMTP clients. But it is neither able to recieve emails nor send it. I tried with various test servers and also the standard gmail/yahoo etc.
Here is the code:
# Copyright 2014-2021 The aiosmtpd Developers
# SPDX-License-Identifier: Apache-2.0
import asyncio
from asyncio.base_events import Server
import logging
import aiosmtpd
from aiosmtpd.controller import DEFAULT_READY_TIMEOUT, Controller
import ssl
from aiosmtpd.smtp import Envelope, Session
from smtplib import SMTP as SMTPCLient
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain('cert.pem', 'privkey.pem')
class ExampleHandler():
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
if address.endswith('#example.com'):
print('not relaying to that domain bro :(')
return '550 not relaying to that domain'
envelope.rcpt_tos.append(address)
print(address+" "+"is added to rcpt_tos")
# Make an envelope for the recipient with the same content.
return '250 OK'
# async def handle_EHLO(self, server, session, envelope):
# print('EHLO from %s' % envelope.mail_from)
# return '250-Hello, how are you?\n250-I am fine\n250 HELP'
async def handle_DATA(self, server, session, envelope):
print('Message from %s' % envelope.mail_from)
print('Message for %s' % envelope.rcpt_tos)
print('Message data:\n')
for ln in envelope.content.decode('utf8', errors='replace').splitlines():
print(f'> {ln}'.strip())
print()
print('End of message')
# Dump the contents of envelope.content to a file.
fi=open('./mailbox/firstletter.txt','w')
fi.write(envelope.content.decode('utf8', errors='replace'))
fi.close()
# print everything in DATA.
# Send the envelope to the recipient.
return '250 Message will be delivered'
#Define Relay server.
async def amain(loop):
cont = Controller(ExampleHandler(),hostname='x.x.x.x', port=25, server_hostname='Galam Limited',ready_timeout=5000)
# Combining ExampleHandler and Controller into a single Controller.
cont.start()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.create_task(amain(loop=loop))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
You can test the server reachability . I am stuck and spent 2 whole days to no avail. The issue is definetely not connectivity, I put the port 25 open. Made sure there are no external issues with godaddy either. Any help will be appreicated.
Edit:1
A quick peak at the wire shark data shows absolutely no packet is being transmitted to the outside when I run the client script.
Here is the clinet script I used for testing.
from smtplib import SMTP as Client
from aiosmtpd.controller import Controller
class controller:
hostname='192.168.1.33'
port=25
client = Client(controller.hostname, controller.port)
r = client.sendmail('a#galam.in', ['tester#192.168.1.200'], """\
From: Anne Person <anne#galam.in>
To: Bart Person <tester#192.168.1.200>
Subject: A test
Message-ID: <ant>
Hi Bart, this is Anne.
""")
SMTP 250 code means that a successful connection has been established however the remote host you are sending mails to might have categorized the domain the mail is being sent from as not legitimate.
This can happen if your domain is not authenticated/verified.
You can relay your messages through a trusted SMTP service like sendgrid
You can also check if your domain is verified by sending a mail from your service to check-auth#verifier.port25.com. Port25 is an automated tool that verified your DNS records, SPF records etc.
Hope this works for you!
I've written a small smtp server in python (taken from the smtpd docs):
import smtpd
import asyncore
class MySMTPServer(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)
return
server = MySMTPServer(('127.0.0.1', 587), None)
asyncore.loop()
I want to be able to send an email from my gmail account (or whatever email provider) to this server. Here's what I've done so far:
Write an MX record on an A-Level domain
Throw the server up on a box that has port 587 opened
Send an email from gmail to someone#myaleveldomain.com
Profit?
Step 4 hasn't really come through. I can't find any logs that offer any info into what happened, according to my server logs the message from gmail never arrived.
Am I doing something wrong? Please help!
I've got a simple SMTP mailing example from here and my modified it. My code is:
import smtplib
sender = 'igor.savinkin#gmail.com'
receivers = ['igor.savinkin#gmail.com']
message = """From: From Igor <igor.savinkin#gmail.com>
To: To Igor Savinkin <igor.savinkin#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message from SMTP python.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email to " + receivers.__str__()
except SMTPException:
print "Error: unable to send email"
Output is:
Successfully sent email to ['igor.savinkin#gmail.com']
Yet, in actuality I find no mails like these in my inbox. The spam folder is checked too!
What's wrong? I use rhc (OpenShift) platform.
You send your mail to a local SMTP server (smtpObj = smtplib.SMTP('localhost')). IMHO it accepts it (request is syntactically correct) but is then not allowed (or not configured) to forward it to gmail. I'm not using OpenShift so I do not know how SMTP is configured there.
You should control how the local SMTP server is configured.
I have a python script to run a SMTP server in localhost. This is my very simple code:
import smtpd
import asyncore
class CustomSMTPServer (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)
server = CustomSMTPServer(('127.0.0.1', 25), None)
asyncore.loop()
If I send an email from an email client running on localhost the email arrives successfully in the STMP server. However, if I send an email from an email client running in a computer located in the same local network (192.168.1.1/24), it doesn't succeed. Here below the error I get from Outlook Express:
The connection to the server has failed. Account 'localhost', Server '192.168.1.115'.
Protocol SMTP, Port: 25, Secure(SSL): No, Socket Error: 10061, Error Number: 0x800CCC0E
Just in case, I deactivated McAfee firewall in both PCs but I still get the same error.
Where can be the problem? Does it have anything to do with the asyncore.loop() method? Thanks!
Your server is running on the loopback interface:
server = CustomSMTPServer(('127.0.0.1', 25), None)
That interface is not reachable from any external network, only from the local machine.
You will need to start your email server on a real network interface (such as 192.168.1.115, based on the error message).
Also, I doubt you'll be able to retrieve any message anyway. You are running an SMTP server: it accepts messages over SMTP but will not provided POP3 / IMAP services, so you can't retrieve messages using a remote email client. The SMTP server can be used to store messages in a local file-based message store though (and en email client running on the same machine could retrieve messages from the file, if correctly formatted).
I am trying to build a small SMTP Server through which I can be able to send some messages. Looking at the smtpd library found that there was something. But I only was able to create a server that reads the email received, but never sent it to the address requested.
import smtpd
import asyncore
class CustomSMTPServer(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)
return
server = CustomSMTPServer(('127.0.0.1', 1025), None)
asyncore.loop()
client:
import smtplib
import email.utils
from email.mime.text import MIMEText
# Create the message
msg = MIMEText('This is the body of the message.')
msg['To'] = email.utils.formataddr(('Recipient', 'recipient#example.com'))
msg['From'] = email.utils.formataddr(('Author', 'author#example.com'))
msg['Subject'] = 'Simple test message'
server = smtplib.SMTP('127.0.0.1', 1025)
server.set_debuglevel(True) # show communication with the server
try:
server.sendmail('author#example.com', ['myadress#gmail.com'], msg.as_string())
finally:
server.quit()
If you really want to do this
then check out the Twisted examples:
http://twistedmatrix.com/documents/current/mail/examples/index.html#auto0
I really don't recommend you write your own MTA (Mail Transfer Agent) as this is
a complex task with many edge cases and standards to have to worry about.
Use an existing MTA such as Postfix, Exim, or Sendmail.