I am able to send the mail to gmail account via SMTP in Python. But when tried doing the same for Outlook - office365, it is throwing the error.
Code to send mail to gmail (working)
import smtplib
sender_email = "ABC#gmail.com"
rec_email = "ABC#gmail.com"
password = input(str("pwd:"))
message = "hey sent using python"
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(sender_email,password)
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email)
code for Outlook(throwing error)
import smtplib
sender_email = "ABC#companydomain.com"
rec_email = "ABC#companydomain.com"
password = input(str("pwd:"))
message = "hey sent using python"
server = smtplib.SMTP('smtp.outlook.com',587)
server.starttls()
server.login(sender_email,password)
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email )
The following error occurs when i run the above outlook code:
Traceback (most recent call last):
File "C:/Users/ABC/Python/Python37/pythonmail.py", line 32, in <module>
server.login(sender_email,password)
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 730, in login
raise last_exception
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful
[BM1PR01CA0154.INDPRD01.PROD.OUTLOOK.COM]')
i even went through the following links:
[https://stackoverflow.com/questions/57203843/unable-to-send-mail-in-python-on-outlook-with-the-smtplib][1]
[https://www.pythonanywhere.com/forums/topic/1961/][2]
[https://stackoverflow.com/questions/66061531/send-mail-from-alias-mail-id-using-python-smtplib][2]
Can somebody help me on how to fix the error??
Meanwhile the below code worked for both gmail and outlook using win32com.client. But i want to do it with SMTP lib. Kindly help
import win32com.client as client
outlook = client.Dispatch("Outlook.Application")
message = outlook.CreateItem(0)
message.Display()
message.To = 'ABC#domain.com'
message.subject = 'Test Mail'
message.body = 'Sending a test mail :)'
message.send
print("mail sent successfully")
Tried by not giving port number and password. It worked.
import smtplib
sender_email = "test_mail#company.com"
rec_email = ["ABC#company.com"]
message = "hey sent using python"
server = smtplib.SMTP('smtp.corp.company.com')
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email )
Related
This question already has an answer here:
UnicodeEncodeError: 'ascii' codec can't encode character ... when sending email
(1 answer)
Closed 9 months ago.
Up until yesterday I had no issue sending emails with python and now for some reason I am getting the following error.
Traceback (most recent call last):
File "main.py", line 20, in <module>
mail(name)
File "/home/runner/mail.py", line 26, in mail
smtpserver.login(gmail_user, gmail_password)
File "/usr/local/lib/python3.7/smtplib.py", line 730, in login
raise last_exception
File "/usr/local/lib/python3.7/smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "/usr/local/lib/python3.7/smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials p17sm967082ils.71 - gsmtp')
I have been using the below code for about 4 months and haven't had any issues. Here is the code I am using to access gmail:
import smtplib
def mail(name):
gmail_user = 'email#gmail.com'
gmail_password = 'password'
emaillist = ['email#email.com']
for email in emaillist:
sent_from = gmail_user
to = email
subject = 'Subject'
body = "Body"
email_text = '''\
From: %s
To: %s
Subject: %s
%s
'''%(sent_from, to, subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, body)
server.close()
print('Email sent!')
except:
print('Oops!')
I have tried changing the use less secure apps in gmail, enabling IMAP, and changing the password for the email account. So far no luck with solving the issue. Any help would be greatly be appreciated.
Google has increased its security policies, I invite you to read this link in the part of: Less secure apps & your Google Account and open the link like bellow ( Less secure app access)
https://support.google.com/accounts/answer/6010255
later Allow access to unsafe applications: YES
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("******#gmail.com", "*******")
msg = "Hello!"
server.sendmail("rajesh.debugs#gmail.com", "rjucsm#gmail.com", msg)
OUTPUT :
C:\Users\Admin\PycharmProjects\Gabbar\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Gabbar/MadhuBhai/t3.py
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/Gabbar/MadhuBhai/t3.py", line 5, in <module>
server.login("******#gmail.com", "******")
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 730, in login
raise last_exception
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtX\n5.7.14 HDzghr7H0UegF2rvoxWT6p9FwK8ct-IgZQXTa09qiineo743EE4PjOLOukbW-7fN2_FfIx\n5.7.14 qBwOghPCGmq1zlaUP3231EHWXgeut6dhRtiEjEVKAd-VKglbnUqvCyPMLKlADKhWt56L_5\n5.7.14 afzoYLGapj8SmZxp_W6VMrkj10aK9xthTsrmUerV9bkqgILAnKh9SWOO2n-7WsHO43reIf\n5.7.14 MQqmW0G2lyXQWbYt-8LxUHRt3ATI8> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 v5-v6sm6337091pfd.1 - gsmtp')
Process finished with exit code 1
Possible duplicate of: SMTPAuthenticationError when sending mail using gmail and python
You will need to look at https://support.google.com/accounts/answer/6010255?hl=en and enable https://myaccount.google.com/lesssecureapps for your mail account.
If you aren't set on using with smtplib, then I would recommend SendGrid for sending emails (if you send < 100 emails/day then it's free).
import sendgrid
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key)
from_email = Email("test#example.com")
to_email = Email("test#example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "content")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
You need to use email.mime along with smtp. Try below:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import smtplib
strFrom = 'xyz.uvw#gmail.com'
strTo = ['efg.abc#gmail.com','hij.lmn#gmail.com']
attachment = '<path to attachment if any>'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'TEST'
msgRoot['From'] = strFrom
msgRoot['To'] = ", ".join(strTo)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
msgText = MIMEText('<b>Summary</b>', 'html')
msgAlternative.attach(msgText)
fp = open(attachment, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtp = smtplib.SMTP("YOUREMAILHOST", 25, timeout=120)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.close()
I am trying to send an email. The code I am using is found below:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email_user = 'email#gmail.com'
email_password = 'password'
email_send = 'receiver#gmail.com'
subject = 'subject'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Hi there, sending this email from Python!'
msg.attach(MIMEText(body,'plain'))
try:
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', port=587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(email_user,email_send,text)
server.quit()
print('successfully sent the mail')
except:
print("failed to send mail")
I get an error "failed to send mail" with the error message:
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t10sm6451859wra.16 - gsmtp')
The error occurs on the server.login() line, I am not able to login.
I checked other post and it says, it has to do with wrong credentials but my credentials are correct. I have check and double checked.
What could be the problem with this and how do I resolve it?
Send an email using python is easy, you may have encountered mistakes in your snippet code above and I am lazy to debug your code. But here might be the code you prefer.
The smtp.gmail.com,465 make your code secure. This snippet of code will send email to recipient through spam but lot number of emails you wish to send, will not be blocked by Gmail, you also can use bot to send email through recipient via this snippet of code.
Send Multiple Recipients
In the to line, just separate recipients by comma
to = [
'<recipient_email_address1>',
'<recipient_email_address2>',
'<recipient_email_address3>']
import smtplib
def sendEmailFunc():
gmail_user = '<your_sender_email_address_here>'
gmail_password = '<credential_password_of_above_email>'
sent_from = gmail_user
to = ['<recipient_email_address>']
subject = '<write_your_email_subject_here>'
body = "<write_your_email_body_here>"
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('====Email Sent Successfully====')
except:
print ('Something went wrong...')
NOTE
Please be careful with your indentation.
Hope this helpful for you.
Thank you.
I'm trying to send a mail with from cgi web console using email input field but it fails with below error in apache logs
Traceback (most recent call last):
File "/opt/apache-dba/cgi-bin/main.py", line 132, in <module>
mail()
File "/opt/apache-dba/cgi-bin/main.py", line 129, in mail
s.sendmail(me, you, msg.as_string())
File "/usr/lib64/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'xxx#adp.com/': (501, '5.1.3 Bad recipient address syntax')}
But I'm able to run the same code and able to receive the mail from python shell
Below is the code, this looks like when I run the code from cgi it is trying to convert mailid from 'xxx#adp.com' to 'xxx#adp.com/' resulting syntax error.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Emailid = xxx#gmail.com
Link='http://google.com'
def mail():
me = "GETS.INDIA.DDS.TAM#gmail.com"
you = str(Emailid)
msg = MIMEMultipart('alternative')
msg['Subject'] = "Upgrade Status Link"
msg['From'] = me
msg['To'] = you
text = '%s' % str(Link)
part1 = MIMEText(text, 'plain')
msg.attach(part1)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
mail()
any help will be greatly appreciated, Thank you
It looks like Emailid should be a string. Try surrounding your test email in quotes to make it a string.
Emailid = 'xxx#gmail.com'
I'm trying to create a daemon which regularly sends me emails and I'm using the following snippet of code to do so.
import smtplib
from datetime import date
from email.mime.text import MIMEText
def send_email():
SMTP_PORT = 587
SMTP_SERVER = 'smtp.mail.com'
SMTP_USERNAME = 'EMAIL'
SMTP_PASSWORD = 'PASSWORD'
EMAIL_TO = ['email#hotmail.com']
EMAIL_FROM = 'EMAIL'
EMAIL_SUBJECT = 'Test!'
DATE_FORMAT = '%d/%m/%Y'
EMAIL_SPACE = ', '
DATA='Email Content'
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + ' %s' % (date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
However, after 5 emails, even though I've added the senders email to my contact list on outlook/hotmail, the daemon returns the following exception:
Sending email! 1/1
Traceback (most recent call last):
File "daemon.py", line 91, in <module>
send_email()
File "daemon.py", line 78, in send_email
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'email#hotmail.com': (550, 'Requested action not taken: mailbox unavailable\nFailure sending mail. Try again later')}
Can anyone advise on how to get around this? Does anyone know of an email service that has been tested which will allow more than 5 emails or how I configure the smtplib to not stop sending after 5 emails to the same address?
UPDATE: When I change the receiving email address from outlook to gmail (another one of my emails) - it returns the same exception even though I've sent no emails to the gmail SMTP server.