How can I send email using Gmail's SMTP without using smtplib? - python

This is my code:
import socket
import base64
s=socket.socket()
s.connect(('smtp.gmx.com',25))
message=s.recv(1024)
print message
s.send("EHLO gmx\r\n")
message=s.recv(1024)
print message
Username=raw_input("Inesrt Username: ")
Password=raw_input("Insert Password: ")
UP=("\x00"+Username+"\x00"+Password).encode("base64")
UP=UP.strip("\n")
print "AUTH PLAIN "+UP
s.send("AUTH PLAIN "+UP+"\r\n")
message=s.recv(10000000)
print message
s.send("MAIL FROM:"+Username+"\r\n")
message=s.recv(10000)
print message
To=raw_input("TO:")
s.send("RCPT TO:"+To+"\r\n")
message=s.recv(10000)
print message
s.send("DATA\r\n")
message=s.recv(100000)
print message
Subject=raw_input("Subject: ")
Text=raw_input("Message:")
s.send("Subject: "+Subject+"\r\n\r\n"+Text+"\r\n.\r\n")
message=s.recv(10000)
print message
s.send("QUIT\r\n")
message=s.recv(100000)
print message
s.close()
It works for regular email, but it does not work for Gmail or Yahoo. How can I send email using Gmail's SMTP using similar code?

Gmail SMTP server does not support plain SMTP protocol. You have to use TLS/SSL and connect to port 465. See this question for more pointers how to do that.

Related

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

Python Email script trouble

I have a script that will be running nightly. I want it to send me an email when it fails to complete. I wrote a short test script to learn how to send an email with Python. In my IDE it runs without error messages but no email. I'm running from one of our servers (not the email server) which doesn't have any email restrictions.
I tried it in the Python shell so I can read any messages:
I tried sending to my gmail account and it get this error:
SMTPRecipientsRefused: {'blahblahblah#gmail.com': (550, '5.7.1 Unable to relay')}
Any ideas??
More info:
I modified the code found here to work with our email.
def send_email(user, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("workemailserver.com")
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
With this I can send an email to my coworkers, but not myself. No biggie because I can use a coworkers email as the sender. Our "email server" relays the messages to office365, so that's why I cant send to my gmail.
My problem is basically solved. But I was never able to get the "simpler" code on top to work when I had tried sending to coworkers?
SMTPRecipientsRefused: (550, '5.7.1 Unable to relay')
This means the server you used can not relay the message to the target recipient. This usually happens when your email server has configuration issues.

how to read the pop server response in python

I am trying to read the response or exception of pop3 hotmail server. its very simple question but i am beginner in python don't know how to read it? this is my code:
import poplib
import sys
host = 'pop3.live.com'
port = 995
email='123456#hotmail.com'
pwd='123456'
server = poplib.POP3_SSL(host, port)
try:
server.user(email)
server.pass_(pwd)
if('+OK'):
print 'Email: '+email+'password: '+pwd
server.quit()
sys.exit(1)
except poplib.error_proto:
if('POP+disabled'):
print 'Email: '+email+'password: '+pwd
server.quit()
sys.exit(1)
elif('authentication+failed'):
print "wronge user and pass. try again"
continue
continue
in exception "if ('POP+disabled')" used to eliminate that user login and password is correct but the account has not enabled POP3 in options.
when I run the above code then it also display email password whether i put wrong password...
Can any body help me please how to handle this problem?
You can use the server.getwelcome() method to check for the server response before proceeding into parsing messages.
The server object lets you request the list of messages after authentication and then you can call retr to retrieve each message.
welcomeresp = server.getwelcome()
if welcomeresp.find("+OK"):
numMessages = len(server.list()[1])
for i in range(numMessages):
for j in server.retr(i+1):
server_msg, body, octets = j
for line in body:
print line
Take a look at the documentation for the POP library for more information and an example:
https://docs.python.org/2/library/poplib.html

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.

No email sending using smtplib - python

import smtplib
sender = 'den.callanan#gmail.com'
receiver = ['callanden#gmail.com']
message = """From: From Person <den.callanan#gmail.com>
To: To Person <callanden#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
print("trying host and port...")
smtpObj = smtplib.SMTP('smtp.gmail.com', 465)
print("sending mail...")
smtpObj.sendmail(sender, receiver, message)
print("Succesfully sent email")
except SMTPException:
print("Error: unable to send email")
I've created two new email accounts (above), both on the same server (gmail) to test this.
It reaches the point in which it prints "trying host and port..." and does not go any further. So the problem should be with the address and port number I entered. But according to gmail's outgoing mail server details i've inputted them correctly. Any ideas what's wrong?
If I remove the port number or try a different port number such as 587 i'm provided with an error.
Sending email via Gmail's SMTP servers requires TLS and authentication. To authenticate, you will need to make an application-specific password for your account.
This script worked for me (though I used my own GMail email address and my own application-specific password). In the code below, replace APPLICATION_SPECIFIC_PASSWORD with the password you generated.
import smtplib
sender = 'den.callanan#gmail.com'
receiver = ['callanden#gmail.com']
message = """From: From Person <den.callanan#gmail.com>
To: To Person <callanden#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
print("trying host and port...")
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("den.callanan#gmail.com", "APPLICATION_SPECIFIC_PASSWORD")
print("sending mail...")
smtpObj.sendmail(sender, receiver, message)
print("Succesfully sent email")
except smtplib.SMTPException:
print("Error: unable to send email")
import traceback
traceback.print_exc()
(To debug the problem, I added the print-traceback code in the except statement. The exceptions had specific information on how to get it to work. The code hung when accessing port 465, I think because of problems with TLS negotiation, so I had to try using port 587; then I got good debugging info that explained what to do.)
You can see info on the SMTP_SSL object here.

Categories