sending Email using outlook through python - python

I am trying to send email through outlook using python I gotTraceback (most recent call last): File "c:\Users\Variable\Documents\python_files\learning_new\sending_email.py", line 23, in <module> session.sendmail(sender_address, receiver_address, text) File "C:\Users\Variable\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 908, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (554, b'5.2.0 STOREDRV.Submission.Exception:OutboundSpamException; Failed to process message due to a permanent exception with message [BeginDiagnosticData]WASCL UserAction verdict is not None. Actual verdict is Suspend, ShowTierUpgrade. OutboundSpamException: WASCL UserAction verdict is not None. Actual verdict is Suspend, ShowTierUpgrade.[EndDiagnosticData] [Hostname=PAXP193MB1710.EURP193.PROD.OUTLOOK.COM]') but the strange thing is that this error not always occurs,sometimes It works and send mails.and
my code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = '''Hello,
This is a simple mail. There is only text, no attachments are there The mail is sent using
Python SMTP library.
Thank You'''
#The mail addresses and password
sender_address = 'Fahe_em#outlook.com'
sender_pass = '*********'
receiver_address = 'fah909190#gmail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.' #The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.office365.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

It just needed few googling to see that you encountered an exception related to your account, due to things like: not being verified, spamming, not upgrading, and more.
Sources: [1], [2], [3]

Related

send email with Gmail Python

I am attempting to send an email, but I run into this error:
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor d2sm13023190qkl.98 - gsmtp')
In the web URL i dont see anything super useful, would anyone have any tips? For SO purposes I left the email account passwords as test versus sharing my person info..
import smtplib
import ssl
# User configuration
sender_email = 'test#gmail.com'
receiver_email = 'test#gmail.com'
password = 'test'
# Email text
email_body = '''
This is a test email sent by Python. Isn't that cool?
'''
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, email_body)
print('Email sent!')
print('Closing the server...')
server.quit()
I tried my best... I think this should work!
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email = "test#gmail.com" # the email where you sent the email
password = "yourPassword"
send_to_email = "yourEmail#gmail.com" # for whom
subject = "Gmail"
message = "This is a test email sent by Python. Isn't that cool?!"
msg = MIMEMultipart()
msg["From"] = email
msg["To"] = send_to_email
msg["Subject"] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()
You must allow the "Less secure apps" in Google configurations.
Here is the link of another thread about it : Link

How to get smtp email log

I want to get a log when I email to the wrong email address.
so, I wrote this command.
mailserver = mymailserver
to_email = emailaddress
from_email = fromaddress
subject = SBJECT
original_message = TEXT
message = MESSAGE
server = smtplib.SMTP(mailserver)
debug = server.set_debuglevel(1)
server.sendmail(from_mail,to_mail, message)
server.quit()
print(debug)
I just want to know connection status log.
wchich code should I edit?
I tried this scripts, but it does not work well.
server = smtplib.SMTP(mailserver)
mail_response = server.sendmail(from_mail,to_mail, message)
server.quit()
print(mail_response)
Thank you for helping me.
Try This and read the docs. Hope it will help you
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
# Or simply skip this part
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = f'The contents of {textfile}'
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Create a email conversation to and fro between multiple user Using python SMTP/IMAP

I need to write a python script that will automatically reply to a mail and I want it to behave like mail thread in gmail where reply mail is linked with original received mail. I do not want to send a separate mail or new mail as a reply.
Can anybody help me?
You can send emails with Pythons smtplib module HTML emails are supported within email module. I have written a small script from a tutorial in the past that might help you out. The script connects to a gmail smtp port and logins to an email account and then sends an email.
import smtplib, ssl, email, random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# set the port and the server adres
smtp_server = "smtp.gmail.com"
port = 587
# Sender email details, this is from where the email is send
sender_email = "<YOUR_EMAIL>"
sender_email_password = "<PASSWORD>"
# This where the email goes to
receiver_email = "<EMAIL>"
# The name is taken from the first part of the email adres, before the '#'-sign
name = receiver_email.split("#")[0]
# Generate the message
message = MIMEMultipart("alternative")
message["Subject"] = str(random.randint(0,1000))
message["From"] = sender_email
message["To"] = receiver_email
# alternative text
text = "Hi there {}, How are you!".format(name)
# Fancy HTML email
html = "<h1>Hi there {}, How are you!!!!</h1>".format(name)
# Set a document as attachment, needs to be in the same directory
filename = "document.txt"
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)
message.attach(part)
context = ssl.create_default_context()
# Send the email
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls(context = context)
server.ehlo()
server.login(sender_email, sender_email_password)
server.sendmail(sender_email, receiver_email, str(message))
except Exception as e:
print(e)
finally:
server.quit()

Cannot send an email with python smtp

I am developing an application using python where I need to send a file through mail. I wrote a program to send the mail but dont know there's something wrong. The code is posted below. Please any one help me with this smtp library. Is there's anything i m missing? And also can someone please tell me what will be the host in smtp! I am using smtp.gmail.com.
Also can any one tell me how can i email a file (.csv file). Thanks for the help!
#!/usr/bin/python
import smtplib
sender = 'someone#yahoo.com'
receivers = ['someone#yahoo.com']
message = """From: From Person <someone#yahoo.com>
To: To Person <someone#yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
You aren't logging in. There are also a couple reasons you might not make it through including blocking by your ISP, gmail bouncing you if it can't get a reverse DNS on you, etc.
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587) # or 465
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(account, password)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except:
print "Error: unable to send email"
I just noticed your request to be able to attach a file. That changes things since now you need to deal with encoding. Still not that tough to follow though I don't think.
import os
import email
import email.encoders
import email.mime.text
import smtplib
# message/email details
my_email = 'myemail#gmail.com'
my_passw = 'asecret!'
recipients = ['jack#gmail.com', 'jill#gmail.com']
subject = 'This is an email'
message = 'This is the body of the email.'
file_name = 'C:\\temp\\test.txt'
# build the message
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = my_email
msg['To'] = ', '.join(recipients)
msg['Date'] = email.Utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(email.MIMEText.MIMEText(message))
# build the attachment
att = email.MIMEBase.MIMEBase('application', 'octet-stream')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)
# send the message
srv = smtplib.SMTP('smtp.gmail.com', 587)
srv.ehlo()
srv.starttls()
srv.login(my_email, my_passw)
srv.sendmail(my_email, recipients, msg.as_string())

Issue with sending mails from a distribution mail id [Python]

I have seen the following question but I still have a few doubts.
Sending an email from a distribution list
Firstly I have an individual mail account as well as a distribution id used for a group in a particular mail server. I am able to send mails from the distribution mail id through outlook just by specifying the From field. It requires no authentication.
I have been using the following code to send mails through my personal account:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
FROMADDR = "myaddr#server.com"
GROUP_ADDR = ['group#server.com']
PASSWORD = 'foo'
TOADDR = ['toaddr#server.com']
CCADDR = ['group#server.com']
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Test'
msg['From'] = FROMADDR
msg['To'] = ', '.join(TOADDR)
msg['Cc'] = ', '.join(CCADDR)
# Create the body of the message (an HTML version).
text = """Hi this is the body
"""
# Record the MIME types of both parts - text/plain and text/html.
body = MIMEText(text, 'plain')
# Attach parts into message container.
msg.attach(body)
# Send the message via local SMTP server.
s = smtplib.SMTP('server.com', 587)
s.set_debuglevel(1)
s.ehlo()
s.starttls()
s.login(FROMADDR, PASSWORD)
s.sendmail(FROMADDR, TOADDR, msg.as_string())
s.quit()
This works perfectly fine. Since I am able to send mail from a distribution mail id through outlook (without any password), is there any way that I can modify this code to send mail through the distribution id? I tried commenting out the
s.ehlo()
s.starttls()
s.login(FROMADDR, PASSWORD)
part but the code gives me the following error:
send: 'mail FROM:<group#server.com> size=393\r\n'
reply: b'530 5.7.1 Client was not authenticated\r\n'
reply: retcode (530); Msg: b'5.7.1 Client was not authenticated'
send: 'rset\r\n'
Traceback (most recent call last):
File "C:\Send_Mail_new.py", line 39, in <module>
s.sendmail(FROMADDR, TOADDR, msg.as_string())
File "C:\Python32\lib\smtplib.py", line 743, in sendmail
self.rset()
File "C:\Python32\lib\smtplib.py", line 471, in rset
return self.docmd("rset")
File "C:\Python32\lib\smtplib.py", line 395, in docmd
return self.getreply()
File "C:\Python32\lib\smtplib.py", line 371, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Would someone kindly help me out here?
reply: retcode (530); Msg: b'5.7.1 Client was not authenticated'
This means you need authentication. Outlook is likely using the same authentication for your existing account (since you only changed the From header).

Categories