How to send email from my own server using python - python

from flask import Flask
from flask_mail import Mail, Message
import os
app = Flask(__name__)
mail_settings = {
"MAIL_SERVER": 'mail.hi.in',
"MAIL_PORT": 465,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": abcde,
"MAIL_PASSWORD": password
}
app.config.update(mail_settings)
mail = Mail(app)
if __name__ == '__main__':
with app.app_context():
msg = Message(subject="Hello",
sender=app.config.get("support#hi.in"),
recipients=["dfjhnk#gmail.com"],
body="This is a test email I sent with Gmail and Python!")
mail.send(msg)
Error Saying:
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

This is a test email I sent with Gmail and Python!
I see that you use Gmail, so if you don't have enabled "Less secure apps on your google account" go here

Related

Python SMTPLIB with proxy support, Gmail connection not allowed

I am succesfully sending emails through gmail app password, python and smtplib.
I am attempting to add proxy support to my script, but I am getting hit by the following error message:
socks.GeneralProxyError: Socket error: 0x02: Connection not allowed by ruleset
Here are the relevant parts of my script:
socks.set_default_proxy(socks.SOCKS5, host, port, True, user, passw)
socks.wrapmodule(smtplib)
session = smtplib.SMTP('smtp.gmail.com', 587)
session.login(sender_address, sender_pass)

How to verify an email in python without sending an email by verifying records?

import smtplib, ssl
import dns.resolver,socket
smtp_server= 'smtp.gmail.com'
port = 465
sender = 'reddy#gmail.com'
pssword = ''
addressToVerify = 'raghavareddy#smatbot.com'
context = ssl.create_default_context()
domain_name = addressToVerify.split('#')[1]
print('domain_name : '+domain_name)
records = dns.resolver.resolve(domain_name, 'MX')
mxRecord = records[0].exchange
print(mxRecord)
host = socket.gethostname()
print('hosttttttttttt==',host)
try:
server = smtplib.SMTP_SSL(smtp_server,port)
server.ehlo()
#server.starttls(context = context)
server.ehlo()
server.login(sender,pssword)
ss = server.connect(str(mxRecord),465)
#print(ss)
pp = server.verify(addressToVerify)
print(pp)
ss = server.rcpt(addressToVerify)
print(ss)
print('ok')
except Exception as e:
print(e)
I was trying to verify the email address but it was throwing an error while it was not connecting mxrecords
[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
It is not connecting to the MX records.
while verifying at
RCPT (503, b'5.5.1 MAIL first. p2-20020a17090ad30200b001cd4989feb7sm14376983pju.3 - gsmtp')
This 503 error code representing that `The server has encountered a bad sequence of commands, or it requires an authentication.
Suggest a standard way of verifying an email, please.
Suggest a standard way of verifying an email, please.
You can not, without sending an email with a nonce, and waiting for it to be used in some timeframe.
Servers won't let you arbitrarily test the existence of email addresses, otherwise this would be an heaven for spammers.

How do I use exchangelib to connect to work email that uses Outlook Web App (OWA)?

I am currently trying to find ways to connect to my work email through a language and python seems to have a library I am looking for. I found the exchangelib library but it is a bit older and I couldn't find anything else to connect to an Exchange Server (my work email aren't "#outlook.com").
I found my username ("WORD\username") and I know my email, password, and the url for the outlook web app email ("www.company.net")
from exchangelib import Account, Configuration, Credentials, DELEGATE, Folder
def connect(SERVER, EMAIL, USERNAME, PASSWORD):
"""
Get Exchange account cconnection with server
"""
creds = Credentials(username=USERNAME, password=PASSWORD)
config = Configuration(server=SERVER, credentials=creds)
account = Account(primary_smtp_address=EMAIL, config=config, autodiscover=False, access_type=DELEGATE)
for item in account.inbox.all().order_by('-datetime_received')[:2]:
print(item.subject, item.body, item.attachments)
def main():
print(connect("www.company.net",
"my#email.net", "WORD\\username", "password"))
This is just supposed to print emails I have but I can't seem to connect because the host fails to respond
Failed to create cached protocol with key ('https://www.company.net/EWS/Exchange.asmx', Credentials('WORD\\username', '********')): HTTPSConnectionPool(host='www.company.net', port=443): Max retries exceeded with url: /EWS/Exchange.asmx (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000169BAF68FD0>: Failed to establish a new connection: [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'))
I tried using the complete url for my OWA email and used exchangelib service_endpoint parameter instead
def connect(SERVER, EMAIL, USERNAME, PASSWORD):
"""
Get Exchange account cconnection with server
"""
creds = Credentials(username=USERNAME, password=PASSWORD)
config = Configuration(service_endpoint=SERVER, credentials=creds)
account = Account(primary_smtp_address=EMAIL, config=config, autodiscover=False, access_type=DELEGATE)
for item in account.inbox.all().order_by('-datetime_received')[:2]:
print(item.subject, item.body, item.attachments)
but it fails to get authorization type
Failed to create cached protocol with key ('https://company.net/.../.../', Credentials('WORD\\username', '********')): Failed to get auth type from service
Is there something I am missing? Could it be because of a security feature on my company's side? I am not sure how to do this properly.
exchangelib uses EWS to connect to the Exchange server. OWA is just a web-based client for Exchange. You cannot connect to it programmatically. Still, it's entirely possible that your server has an EWS endpoint you can connect to.
You need to either enable autodiscover to find the EWS endpoint automatically, or ask your Exchange server admins for the correct endpoint for EWS.

how to fix this ConnectionRefusedError? [duplicate]

This question already has answers here:
Configure Flask-Mail to use GMail
(2 answers)
Closed 3 years ago.
when i execute this code it shows ConnectionRefusedError: [WinError 10061] No connection could be made because the
target machine actively refused it
import os
import smtplib
from flask import *
from flask_mail import *
app = Flask(__name__)
mail = Mail(app)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USERNAME'] = os.environ.get('User' )
app.config['MAIL_PASSWORD'] = os.environ.get('Password' )
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = True
#app.route('/')
def index():
msg = Message('HEllo',sender=["joyciimmaculate#gmail.com"], recipients = ["joyciimmaculate#gmail.com"])
msg.body = "hi bulk sms"
msg.html ="<img src="/static/deepa.jpg" style='width:500px;height:228px;'>"
mail.send(msg)
return "mail sent"```
Based on the description of the error, this is not a problem with your Python code, but rather that the network connection to smtp.gmail.com is being blocked/rejected (possibly by a firewall or some other network issue).
Note that if you are running this on a home machine, most ISPs will actively block outbound SMTP connections to anything except the ISP's own SMTP servers (some hosting providers also do the same), to prevent spammers from exploiting the service. You may need to change your settings to use your ISP's outbound mail host instead of connecting directly to smtp.gmail.com.

Read emails from imap or pop3 server

My task is to read the email using imap or pop3 server address. I am trying to accomplish this task using python. All the sample codes avaliable to do this task throw the error mentioned below
"error: [Errno 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"
What might the problem be , Is it my local firewall settings or maybe due to some other reason...????
import imaplib
imap_host = 'imap.gmail.com'
imap_user = '****#gmail.com'
imap_pass = '****'
## open a connection
imap = imaplib.IMAP4_SSL(imap_host)
## login
imap.login(imap_user, imap_pass)
and
import sys
import chilkat
imap = chilkat.CkImap()
# Anything unlocks the component and begins a fully-functional 30-day trial.
success = imap.UnlockComponent("Anything for 30-day trial")
if (success != True):
print(imap.lastErrorText())
sys.exit()
# Turn on session logging:
imap.put_KeepSessionLog(True)
# Connect to GMail
# Use TLS
imap.put_Ssl(True)
imap.put_Port(993)
success = imap.Connect("imap.gmail.com")
if (success != True):
print(imap.lastErrorText())
sys.exit()
# Login
# Your login is typically your GMail email address.
success = imap.Login("***#gmail.com","*****")
if (success != True):
print(imap.lastErrorText())
sys.exit()
# Select an IMAP mailbox
success = imap.SelectMailbox("Inbox")
if (success != True):
print(imap.lastErrorText())
sys.exit()
# Show the session log.
print(imap.sessionLog())
# Disconnect from the IMAP server.
success = imap.Disconnect()
First I would suggest doing a simple network sanity test eg: with Telnet as follows:
telnet imap.gmail.com 993
If networking is happy you should see a response like:
Trying 64.233.188.109...
Connected to gmail-imap.l.google.com.
Escape character is '^]'.
It also might be worth checking out the gmail help page for IMAP
https://support.google.com/mail/accounts/answer/7875

Categories