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.
Related
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)
I am trying to send an email using a python script like so:
import smtplib, ssl
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "my#gmail.com"
receiver_email = "receiver#gmail.com"
password = "123456"
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
but unfortunately, Gmail blocks this connection, after running this code I receive an email saying that someone tried to access my account from an app that is not owned by Google, does anyone know a solution to this problem?
I want to send mail for different cases in my python program, but my 'message' (check program) in each case is different, how do I solve this ?
I want to send mail with different messages each time using the same user defined function, that is, sendmail(mail,message)
def sendmail(mail,message):
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "something#gmail.com"
receiver_email = mail
password = 'password123'
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
message = f"""\ #my first message
Subject: Use OTP {no} Dear {extname(am1)},
Use OTP {no} to access your account.
Don't share it with someone else. """
sendmail(mail,message)
message = f'''\ #my second message
Subject: ZABANK: Current Balance
Dear {extname(am1)},
Your current balance is {extbal(am1)} rupees. '''
sendmail(mail,message)
I ended up getting my first message twice.
Here, mail is not required as it is a variable assigned to another user-defined function.
You cannot recall the function twice as it will require two simultaneous SMTP logins,
that is logging into your account when you are already logged in(hence the 2nd msg is not sent). you can overcome this by iterating over a list of your messages
#please change your funtion name to avoid collision with the smtp.SMTP.sendmail method
def usersendmail(mail,message):
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "something#gmail.com"
receiver_email = mail
password = 'password123'
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
for msg in messagelist:
server.sendmail(sender_email, receiver_email, msg)
usersendmail("them#gmail.com",["mymessage1","mymessage2"])
With some help off of here, I've set up some code to send emails via Python using SMTP. However the subject does not work. How can I also print variable values in the email body?
port = 587 # For starttls
smtp_server = "smtp.server.com"
sender_email = "sender#outlook.com"
receiver_email = "receiver#outlook.com"
password = "password"
message = """ Subject: Subject
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
Please could you inform me as to:
How to correctly add a subject so that it correctly appears when the email is sent
How to include a print of a variable
Currently the only thing which appears in the email is "This message is sent from Python"
SUBJECT = "SUBJECT of mail"
AGE = 18
message = "Subject: {}\n\n My age is {}".format(SUBJECT, AGE)
you can use format function of string in python to use variable. and \n\n is necessary to differ subject and message
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.