Python send a mail to the user using local smtp server - python-3.x

I want to send a simple text message to the user from local smtp server. When i am using the following code i am getting the following error
#!/usr/bin/python
import smtplib
receivers = ['to#todomain.com']
message = "hello"
Subject: "SMTP e-mail test
This is a test e-mail message."
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
i am getting the following error:
[WinError 10061] No connection could be made because the target machine actively refused it
How to resolve this error.

If this happens always, it literally means that the port is blocked by your firewall.
(What port are you listening on?)
you have to open port 25 if you want send mails from your machine.
Of course also a mail server/service should be running.

Related

Gramex SMTP Email Issue

I have to send an email from python function to multiple users with dynamic content.
I have given email details in gramex.yaml as below
email:
barcode-mail-service:
type: gmail
email: gramex.guide#gmail.com
password: alphaBetaGamma
In my python function I have implemented mail functionality as below:
def email_users(_pending_users, approval):
mailer = service.email['barcode-mail-service']
content = []
if approval == 'Approved':
content = [f"Hi {obj['user']},\n\n \
Welcome to the Service online portal!"
for obj in
_pending_users.to_dict('r')
]
else:
content = [f"Hi {obj['user']},\n\n \
Your request has been rejected by the approver!"
for obj in _pending_users.to_dict('r')
]
to_list = _pending_users['email'].tolist() #gets list of all email ids
for index in range(len(to_list)): #loops over each mail id and sends the email
mailer.mail(
to=to_list[index],
subject=f'Barcode User Access {approval}',
html=content[index]
)
When I execute the above function I get the following error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
How can I fix this?
This seems to be a Firewall issue. SMTP internally uses port 25 for sending email. Enable (Allow) port 25 on your system and try if that works. You would need to enable this port on the server as well during deployment.
Note: Check which port is being used for sending the email by your Email Exchange
You can check this link to enable on Windows OS

Connection Refused Error When Trying to Connect to Outlook Using Python's poplib

I am trying to connect to Outlook using POP3 in python.
mailbox = poplib.POP3_SSL('outlook.office365.com', 995)
And I am getting the following error:
[WinError 10061] No connection could be made because the target machine actively refused it
I am using a VPN, and can ping 'outlook.office365.com' without issue. I also tried 'pop-mail.outlook.com' and 'pop3.live.com' as I saw them mentioned as hostnames online, and received the same error. Please let me know if there is any more useful information I can provide.
for the office 365 email settings it seems that the port for POP is 903. You can try using the settings in the web under Microsoft365 to also try fetching your email with IMAP.
Just to save you same time I wrote down some working lines using imap for fetching your emails and a simple code for sending using smtp
import smtplib
import imaplib
import ssl
def send_email():
send_port = 587
with smtplib.SMTP('smtp.office365.com', send_port) as smtp:
#Need a ehlo message before starttls
smtp.ehlo()
smtp.starttls()
# Server login
smtp.login(<user-email>, <password>)
# Email data
sender_email = <user-email>
receiver_email = <destination-email>
email_subject = <some-subjetct>
email_body = <some-body>
message = 'Subject: {}\n\n{}'.format(email_subject, email_body)
smtp.sendmail(sender_email, receiver_email, message)
smtp.quit()
def receive_email():
receive_port = 993
with imaplib.IMAP4_SSL('outlook.office365.com', receive_port) as imap:
# Server login
imap.login(<youremail>, <password>)
# Get the list of folders in you email account and some extra info.
retcode, folders = imap.list()
# status of the fetch
print ('Response code:', retcode)
# folders and info of hierarchies
print ('Response code:', folders)
imap.close()
#Test
send_email()
receive_email()
Be aware that this code needs the imap and smtp port open on your firewall.
Also use same user-email and password as you were using https://www.office.com/

Connect to SMTP relay in Azure VM with O365 Account fails

How can I use from a VM (linux) where a Java application is running a SMTP Server/relay?
For connecting to SMTP I want to use an O365 account, so configuration looks like:
host: smtp.office365.com
port: 587
TLS: true
uid: UID-O365
pwd: PWD-O365
As response I get:
An error has occurred with sending the test email:
MailException: com.sun.mail.smtp.SMTPSendFailedException:
501 5.1.7 Invalid address [AM4P190MB0211.EURP190.PROD.OUTLOOK.COM]
;
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 501 5.1.7 Invalid address
[AM4P190MB0211.EURP190.PROD.OUTLOOK.COM]
remark: The application that wants to connect runs on java, what is probably unimportant
The server is telling you that the address "AM4P190MB0211.EURP190.PROD.OUTLOOK.COM" that you're using in your message as a sender or recipient address is not a valid email address. It at least needs a "#" in there somewhere. You can get more detail in the JavaMail debug output.
The solution is simple: sender email address (what was not listed above) and UID must be the same

Expected response code 250 but got code "", with message "" When sending emails with Amazon SES and Swiftmailer

Sending emails that way used to work fine but the other day, in the mail of a script sending a lot of emails, I started getting this error for every email sent:
"Expected response code 250 but got code "", with message """
I cannot find any help on the Amazon SES website.
Many thanks.
in my case it was because of email processing handled by queue worker, and it looks like transport is open until worker process end, so Swiftmailer send many emails in long-running connection and at some point SMTP server closes connection on timeout.
this code helps if used before $this->mailer->send()
if ($this->mailer->getTransport()->isStarted()) {
$this->mailer->getTransport()->stop();
}

web2py: sending email: lost connection after EHLO from localhost

I'm trying to send email in web2py using the postfix server on Centos. I can send it successfully using the gmail SMTP server, but when I change the settings to:
mail.settings.server='127.0.0.1:25'
mail.settings.login = 'user:pass'
no email gets delivered. I checked the logs and I see this:
postfix/smtpd[31521]: connect from localhost[127.0.0.1]
postfix/smtpd[31521]: lost connection after EHLO from localhost[127.0.0.1]
postfix/smtpd[31521]: disconnect from localhost[127.0.0.1]
I am able to send email successfully using the local mail command. I am new to linux, so please bear with me.
depending on your version of web2py try setting
mail.settings.tls = False

Resources