No email sending using smtplib - python - 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.

Related

Send email at specific time with millisecond precision

I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.
I could use gmail schedule send feature but there is X delay between sending email from gmail server to school email and it potentially should be achieveable to cut it down slightly so I thought about python script to do it. I think I can get around sending it at a given time but struggle to actually send the message.
There are threads in stackoverflow suggesting python solution e.g.: How do I schedule an email to send at a certain time using cron and smtp, in python? but unfortunately it looks like gmail disabled the option to send mails from non-authorized apps.
Other threads suggest that enabling less secure apps is needed. Unfortunately, this setting has been closed by Google. What could be the way around it?
My sample code:
`
def send_mail():
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo() # optional
print('Server initialized')
sent_from = gmail_user
to = ['xxxxxxxx#gmail.com']
subject = 'my subject'
body = 'my body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server_ssl.sendmail(sent_from, to, email_text)
server_ssl.close()
except Exception as inst:
print('Something went wrong')
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst)
`
is returning an error:
<class 'smtplib.SMTPSenderRefused'> (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError
You need to supply the login to the account, as well as an apps password. You cant just send an email without being authenticated to the mail server.
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
print( 'waiting to login...')
server.login(sender_email, password)
print( 'waiting to send...')
server.sendmail(sender_email, receiver_email, text)

How to use SMTP with Apple iCloud Custom Domain

I would like to use Python's SMTP to send automated emails with a custom domain iCloud+ email address. However, I can't get logged into the SMTP servers. I will always either get "Mailbox does not exist" or "Authentication failed".
From the Apple support pages it seems like you need to use SSL over port 587. Additionally, they want you to generate an "app-specific password" for outside applications. This led me to the following code:
import smtplib, ssl
smtp_server = "smtp.mail.me.com"
port = 587 # For SSL
# Create a secure SSL context
context = ssl.create_default_context()
sender_email = "me#example.com" # Enter your address
receiver_email = "you#example.com" # Enter receiver address
password = "some,password" # app specific password from Apple ID settings
message = """\
To: {to}
From: {sender}
Subject: Hello There
This was sent through Python!
""".format(to=receiver_email, sender=sender_email)
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
# Send email here
server.sendmail(sender_email, receiver_email, message)
However, this was still giving me a connection error. Only when I changed the last part to use TLS instead would it connect and give me an authentication error. This was taken from this question: SMTP_SSL SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:590)
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
# Send email here
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
import traceback
print(traceback.format_exc())
finally:
server.quit()
So how can I use my custom domain address with Apple's iCloud+ service with Python's SMTP?
Just before I was going to ask this question, I solved it!
After reading this reddit post, I figured that all custom domain iCloud+ accounts are actually alias of some sort to the main iCloud account. So, I tried logging into my "main" iCloud account. This worked with the above code and sent the email! However, the from was still not my custom domain email address.
This is a somewhat easy fix though, simply modify the "From: <sender>" line in the email body. I'm not sure if this should be done (since it's technicaly faking who you are) but it seems to work. If any email experts know of better ways to do this please comment/answer though! The following code is what I used:
sender_email = "me#icloud.com" # this is who we actually are
sender = "me#example.com" # this is who we appear to be (i.e. custom domain email)
receiver_email = "you#example.com" # this is to who we have sent the email
message = """\
To: {to}
From: {sender}
Subject: Hello There
This was sent through Python!
""".format(to=receiver_email, sender=sender) # this is what changed, we use an alias instead
# ...
server.sendmail(sender_email, receiver_email, message)

send email with python - unauthorized sender address [duplicate]

This question already has an answer here:
Getting unauthorized sender address when using SMTPLib Python
(1 answer)
Closed 2 years ago.
I tried sending an email with python using the email-provider "web.de".
I activated email protocols in the settings of the email service provider.
The following error message occurs:
(554, b'Transaction failed\nUnauthorized sender address.')
It should be possible to do it because my email programs can send emails.
import smtplib, ssl
smtp_server = "smtp.web.de"
port = 587 # For starttls
sender_email = "someemail#web.de"
password = input("Type your password and press enter: ")
receiver_email = "another#web.de"
message = "Subject: Hi there\n\nThis message is sent from Python."
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
First of all, I would advise you to use sendinblue, it is awesome and it is free to some extent.
Coming to your question, I don't think you should be asking for the senders password, since they might not give it to you. Next I think the senders email should have the email that you have registered with your email provider, not the email a person provides. The receiver email is good to go I guess. But I think this part has some problems:
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
I think you forgot to write the subject of the email, which is likely triggering the error. I have never sent emails with python, but I have used python web framework django, and it shows error if the subject of the email is not provided.
Try this:
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail("This is the subject", sender_email, receiver_email, message)
also i think the receiver email should be a list, not just a string, because the number of recipients can change. Put it in a list like this even if you don't want to send it to a lot of people.
receiver_email = ["another#web.de"]
You can new recipients by putting a comma and writing the second recipient in quotes.

Troubleshooting smtplib with cPanel email - Python3

I have tested the below code with gmail credentials and it works perfectly, however, when I try to use an email created within a cPanel it does not work. I am certain that the credentials are correct and that I am not being blocked by the server as my email client is working and I can telnet to it.
Is there a way to somehow produce logs to see why exactly it's failing? Using print statements I found that it fails when it gets to the server variable.
import config
import smtplib
class EmailAlert(object):
"""Class for sending email alert from slave account"""
def __init__(self, subject, msg):
self.subject = subject
self.msg = msg
def send_email(self):
try:
server = smtplib.SMTP(config.OUTGOING_SERVER) #It fails here and goes to except
server.ehlo()
server.starttls()
server.login(config.FROM_EMAIL_ADDRESS, config.PASSWORD)
message = 'Subject: {}\n\n{}'.format(self.subject, self.msg)
server.sendmail(config.FROM_EMAIL_ADDRESS,
config.TO_EMAIL_ADDRESS,
message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
email = EmailAlert("Test", "test")
email.send_email()
I found that using port 587 works even though the port shown in cPanel's is usually 465.

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

Categories