Office365 smtp server does not respond to ehlo() in python - python

I am trying to use Office365 smtp server for automatically sending out emails. My code works previously with gmail server, but not the Office365 server in Python using smtplib.
My code:
import smtplib
server_365 = smtplib.SMTP('smtp.office365.com', '587')
server_365.ehlo()
server_365.starttls()
The response for the ehlo() is: (501, '5.5.4 Invalid domain name [DM5PR13CA0034.namprd13.prod.outlook.com]')
In addition, .starttls() raises a SMTPException: STARTTLS extension not supported by server
Any idea why this happens?

The smtplib ehlo function automatically adds the senders host name to the EHLO command, but Office365 requires that the domain be all lowercase, so when youe default host name is uppercase it errors.
You can fix by explicitly setting sender host name in the ehlo command to anything lowercase.
import smtplib
server_365 = smtplib.SMTP('smtp.office365.com', '587')
server_365.ehlo('mylowercasehost')
server_365.starttls()

I had to put SMTP EHLO before and after starttls().
Thanks!
import smtplib
server_365 = smtplib.SMTP('smtp.office365.com', '587')
server_365.ehlo('mylowercasehost')
server_365.starttls()
server_365.ehlo('mylowercasehost')

Related

Getting errors connecting to mail servers using SMTP in python

I want to send a mail using smtplib in python. I tried to connect to the gmail server and protonmail server.But getting these errors,
When trying to connect to Gmail server,
import smtplib
server=smtplib.SMTP('smtp.gmail.com',465)
Error: "A connection attempt failed because the connected party did not properly respond after a period of time"
When trying to connect to protonmail server,
import smtplib
Server=smtplib.SMTP('127.0.0.1',1025)
Error: "No connection could be made because the target machine actively refused it."
Please let me know how can I resolve it.
Try this for email,
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("yourmail#gmail.com", "yourpassword")

Send email ( python smtp ) to a specific domain (not .Gmail)

import smtplib
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = 'example1#gmail.com'
#Sender
msg['To'] = 'example2#uc.cl'
#Receiver
msg['Subject'] = 'python'
message = ' Wena mimo, como estai mimo'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('example1#gmail.com', 'password')
#login to the account
mailserver.sendmail('example1#gmail.com','example2#uc.cl',msg.as_string())
mailserver.quit()
#I make a code that sends emails to differents mail(example #gmail and
#corporative ) but i try to send mail to XXXXXXXX#uc.cl (https://www.uc.cl) but this mail dont receive the message
This is a code for Python3 in Ubuntu 18.04 I dont know if the problem is the port:587 or the domain uc.cl or the code, maybe the domain uc.cl takes a high level on this security
THis domain its from a University
I assume the school mail server might try to block the mail coming from your python server.
A few things you could try...
Sending the email while connected to the school wifi. Maybe they don't block internal traffic
Try sending to a email server you set up just to check your code is working right
Make a new email account yahoo, etc and login with the code above and try sending to the other accounts you can test with. This should give you a good idea what is occuring.

how to send email with python directly from server and without smtp

I'm php programmer and with php you can send email with server directly, for example this code send email to client:
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
but in python you have to use smtplib and gmail or hotmail servers for sending email.
I wonder is there anyway to send email with python direct from server?
Other Options
When you use the mail functionality in PHP it is using the local sendmail of the host you are on, which in turn is simply a SMTP relay locally, of course locally sending emails is not really suggested as these are likely not have a good delivery rate due to DKIM, SPF and other protection mechanisms. If you care about deliverability I would recommend using either
An external SMTP server to send mail via which is correctly configured for the sending domain.
An API such as AWS SES, Mailgun, or equivalent.
If you do not care about deliverability then you can of course use local SendMail from Python, SendMail listens on the loopback address (127.0.0.1) on port 25 just like any other SMTP server, so you may use smtplib to send via SendMail without needing to use an external SMTP server.
Sending Email via Local SMTP
If you have a local SMTP server such as SendMail check it is listening as expected...
netstat -tuna
You should see it listening on the loopback address on port 25.
If it's listening then you should be able to do something like this from Python to send an email.
import smtplib
sender = 'no_reply#mydomain.com'
receivers = ['person#otherdomain.com']
message = """From: No Reply <no_reply#mydomain.com>
To: Person <person#otherdomain.com>
Subject: Test Email
This is a test e-mail message.
"""
try:
smtp_obj = smtplib.SMTP('localhost')
smtp_obj.sendmail(sender, receivers, message)
print("Successfully sent email")
except smtplib.SMTPException:
print("Error: unable to send email")

How to create a free SMTP server

I am not at all familiar with SMTP but I am working on sending emails through Python code. I have the code but I need to pass SMTP host name for it to actually work. Is there any service which provides a free SMTP service that I leverage for testing out my code? I looked around to create my own SMTP server but couldn't find something that provides a step by step guide to create a SMTP server. I want to create a free server(or if there is any free service) that will provide me with a host name(ip address) so that I can put that host name in my python code and execute it from any machine.
If anyone can point me in the right direction it will be helpful.
import smtplib
username = 'user'
password = 'pwd'
from_addr = 'username#gmail.com'
to_addrs = 'username#gmail.com'
msg = "\r\n".join([
"From: username#gmail.com",
"To: username#gmail.com",
"Subject: subject",
"",
"message"
])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
You can use mutt linux command also here.
See :
https://docs.python.org/3/library/smtplib.html
https://support.google.com/a/answer/176600?hl=en
You need service like https://mailtrap.io/. You'll get SMTP server address (eventually port number) that you point your application to. All e-mails produced by your application will be then intercepted by mailtrap (thus not delivered to the real To: address).
They offer free variant that seems to be suitable for your needs.

AOL mail rejected using smtplib

I'm using smtplib to send email via AOL account, but after successful authentication it gets rejected with following error.
reply: '521 5.2.1 : AOL will not accept delivery of this message.\r\n'
reply: retcode (521); Msg: 5.2.1 : AOL will not accept delivery of this message.
data: (521, '5.2.1 : AOL will not accept delivery of this message.')
Here's explanation for this error.
The SMTP reply code 521 indicates an Internet mail host DOES NOT ACCEPT
incoming mail. If you are receiving this error it indicates a configuration
error on the part of the recipient organisation, i.e. inbound e-mail traffic
is being routed through a mail server which has been explicitly configured
(intentionally or not) to NOT ACCEPT incoming e-mail.
Recipient mail (in my script) is valid (gmail) address and after this debug message mail gets rejected.
send: 'Content-Type: text/plain; charset="us-ascii"\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: 7bit\r\nSubject: My reports\r\nFrom: myAOLmail#aol.com\r\nTo: reportmail#gmail.com\r\n\r\nDo you have my reports?\r\n.\r\n'
Here's short version of code:
r_mail = MIMEText('Do you have my reports?')
r_mail['Subject'] = 'My reports'
r_mail['From'] = e_mail
r_mail['To'] = 'reportmail#gmail.com'
mail = smtplib.SMTP("smtp.aol.com", 587)
mail.set_debuglevel(True)
mail.ehlo()
mail.starttls()
mail.login(e_mail, password)
mail.sendmail(e_mail, ['reportmail#gmail.com'] , r_mail.as_string())
Is this some kind of permission problem because I'm successfully sending same email with Yahoo account without any problems?
I guess that AOL doesn't allow relay access by default or you have not configured it manually. The error you get says that aol doesn't have recipient you want to send message. In this case if you want to send email to gmail account try to connect to gmail SMPT server instead of AOL.
Change smpt server to gmail-smtp-in.l.google.com for example and turn off authentication.
Was running into 5.2.1 : AOL will not accept delivery of this message. from the AOL SMTP relay myself. What I ended up needing was valid From and To headers in the MIME message body, as opposed to just the SMTP connection.
In your particular case there could be any number of reasons for getting this 5.2.1 bounce. The postmaster.aol.com site has some helpful tools to diagnose, as well as some pretty vague documentation for this specific error message. In my case I ended up packet sniffing the SMTP messages that my Thunderbird email client was sending vs. the Python script, and eventually spotted the difference.
postmaster.aol.com documentation:
https://postmaster.aol.com/error-codes
AOL will not accept delivery of this message
This is a permanent bounce due to:
RFC2822 From domain does not match the rDNS of sending server.
RFC 2822 FROM address does not have an A record and is not a valid domain.
IP has a poor reputation and mail is sent to multiple recipients.
There are multiple From address in the mail headers and the IP reputation is poor.
My Python function for sending mail through smtp.aol.com:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def genEmail(user, passwd, to, subject, message):
smtp=smtplib.SMTP_SSL('smtp.aol.com',465)
smtp.login(user, passwd)
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = user # This has to exist, and can't be forged
msg['To'] = to
msg.attach(MIMEText(message, 'plain'))
smtp.sendmail(user, to, msg.as_string())
smtp.quit()

Categories

Resources