How to recive an email with attachment - python

I was asked to recive an email using any coding language ( I know java and C but python will be much easier I think but I hope someone can help me choose) then look for the word "cat" inside the body of the email then run the python file attachment which is attached to the mail and send back the output of the file to the sender if the word cat is in the message ( if the word wasnt there or the file returned an exception then return the the problem ) here is what I did so far :
import email
import imaplib
import smtplib
from email.message import EmailMessage
def send_email():
sender_email = 'momo#gmail.com'
password = '123456789'
rec_email ="koko#gmail.com"
message = input(str("enter your message below : "))
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 has been sent to " , rec_email )
def recive_and_check():
EMAIL = 'nono#gmail.com'
PASSWORD = '123456789'
SERVER = 'imap.gmail.com'
# connect to the server and go to its inbox
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
mail.select("inbox")
#I used several tutorials on youtube from here don't really understand what I wrote
status, data = mail.search(None, 'ALL')
inbox_item_list = data[0].split()
most_recent = inbox_item_list[-1]
oldest = inbox_item_list [0]
email_data = mail.fetch(most_recent,'(RFC822)')
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
email_message: EmailMessage = email.message_from_bytes(envelope, _class=EmailMessage)
for email_message_part in email_message.walk():
if email_message_part.is_attachment():
Run(email_message_part)

Related

Send multiple mails hiding recipent in Python

How can I send multiple mails with a hidden recipient?
I can currently send mails, but people who receive it can see the recipient.
My code looks like this:
import smtplib
from email.message import EmailMessage
email_subject = "Good morning"
sender_email_address = "user#outlook.com"
receivers_email_address = ['reciever1#gmail.com', 'reciever2#gmail.com']
email_smtp = "smtp.office365.com"
email_password = "MyPassword"
# Create an email message object
message = EmailMessage()
# Configure email headers
message['Subject'] = email_subject
message['From'] = sender_email_address
message['To'] = ", ".join(receivers_email_address)
# Read file containing html
with open('message.html', 'r') as file:
file_content = file.read()
# Add message content as html type
message.set_content(file_content, subtype='html')
# Set smtp server and port
server = smtplib.SMTP(email_smtp, '587')
# Identify this client to the SMTP server
server.ehlo()
# Secure the SMTP connection
server.starttls()
# Login to email account
server.login(sender_email_address, email_password)
# Send email
server.send_message(message)
# Close connection to server
server.quit()
You don't need to send multiple messages. Just don't put the recipients explicitly in the headers.
The following implements this by putting the recipients in the Bcc: header.
import smtplib
from email.message import EmailMessage
email_subject = "Good morning"
sender_email_address = "user#outlook.com"
receivers_email_address = ['reciever1#gmail.com', 'reciever2#gmail.com']
email_smtp = "smtp.office365.com"
email_password = "MyPassword"
message = EmailMessage()
message['Subject'] = email_subject
message['From'] = sender_email_address
# The message needs to have a To: header
# - putting yourself is an old convention
message['To'] = sender_email_address
message['Bcc'] = ",".join(receivers_email_address)
with open('message.html', 'r') as file:
file_content = file.read()
message.set_content(file_content, subtype='html')
with smtplib.SMTP(email_smtp, '587') as server:
server.ehlo()
server.starttls()
server.login(sender_email_address, email_password)
server.send_message(message)
server.quit()
Of course, if you really need to To: header to indicate the actual recipient, you will need to generate a unique message for each of them.
This relies on the SMTP server to read and strip off the Bcc: header. If you can't rely on yours to do that, you can explicitly use the legacy sendmail method of the smtplib module, which lets you explicitly pass in the list of actual recipients separately from the message. Then you can also avoid the pesky copy to yourself.
To briefly recap, SMTP doesn't really care what's in the To: or Cc: headers; the actual list of recipients is communicated separately, before you submit the actual message. This is called the SMTP envelope.
I made a loop to send individually. Instead of sending it to multiple people in a group.
import smtplib
from email.message import EmailMessage
email_subject = "Good morning"
sender_email_address = "user#outlook.com"
receivers_email_address = ['reciever1#gmail.com', 'reciever2#gmail.com']
email_smtp = "smtp.office365.com"
email_password = "MyPassword"
# Read file containing html
with open('message.html', 'r') as file:
file_content = file.read()
# Set smtp server and port
server = smtplib.SMTP(email_smtp, '587')
# Identify this client to the SMTP server
server.ehlo()
# Secure the SMTP connection
server.starttls()
# Login to email account
server.login(sender_email_address, email_password)
# Send email
for receiver in receivers_email_address:
# Create an email message object
message = EmailMessage()
message['Subject'] = email_subject
message['From'] = sender_email_address
message['To'] = receiver
# Add message content as html type
message.set_content(file_content, subtype='html')
server.send_message(message)
# Close connection to server
server.quit()

Send mail with python

I'm trying to send email with python.
In the function server.sendmail, when I replace message by a "example text with double quote", I receive my email with the good message.
Now, when I try to send a file content saved in my "message" variable, I receive a empty mail, but if I print my variable, the content is correct.
Have you an idea ?
Thx !
import smtplib, ssl
import os
smtp_adress = 'smtp.gmail.com'
smtp_port = 465
email_adress = 'xxx#gmail.com'
email_password = 'xxx'
email_receiver = 'xxx#hotmail.fr'
# message
file = open('dl_link', 'r')
line = file.readlines()
file.close()
message = line[0]
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_adress, smtp_port, context=context) as server:
server.login(email_adress, email_password)
server.sendmail(email_adress, email_receiver, message)
print(message)

Send personalized email with python

I'm a beginner trying to send a personalized email with python.
import smtplib, ssl
def read_creds():
user = passw = ""
with open("credentials.txt", "r") as f:
file = f.readlines()
user = file[0].strip()
passw = file[1].strip()
return user, passw
port = 465
sender, password = read_creds()
receive = sender
message = """\
Subject: Python
This is from python!
"""
context = ssl.create_default_context()
print("Starting to send")
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, receive, message)
print("email sent.")
I want to add a personalized code (which could be, for example, 123456) to every email, but from the tutorial I've read I can't understand how to do it.
You need to identify the way to retrieve a list of contacts from a file or from the database. For the simplicity I'll use an array.
Start with updating your message to support custom messages:
message = """
Subject: Message subject
Hi {name}, you have got a personal message!
"""
Then update the logic behind sending the emails and add recipients into the array (in real life use the DB or file):
recipients = [{"email":"email1#aol.com", "name":"Misha"},{"email":"email2#aol.com", "name":"Andrey"}]
print("Starting to send")
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(sender, password)
for recipient in recipients:
server.sendmail(sender, recipient["email"], message.format(name=name))

Python sending email script not getting credentials from external file

import smtplib
import os
import time
def send_email(contacts):
try:
user= passw=""
with open("credentials.txt", "r") as f:
file = f.readlines()
user = file[0].strip()
passw = file[1].strip()
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls() # it is necessary to start this before login
server.login(user, passw) # login credentials
subject = "Assignment Task for Working student job"
msg = "This is a msg body of assignment. "
message = 'Subject: {}\n\n{}'.format(subject, msg)
for i in contacts:
server.sendmail(user, contacts, message)
print(f"successfully sent email to {i} and wait for 10 seconds" )
time.sleep(10)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
if __name__ == "__main__":
#sender, password = read_creds()
contacts = ['editorawais#gmail.com', 'editorawais#yahoo.com', 'editorawais#live.com','techwpblog#gmail.com']
send_email(contacts)
I created this email script. But now i am getting error on login. My credentials.txt is just of two lines.
"Email address"
"Password"
Please can anybody help me where i am missing something. And the correct way possibly. Thanks
Lose the quotation marks if you indeed have those in the txt file. Python will try to plug in everything on the first and second line including the "" try just doing this in your .txt file.
email
password

Send an email in python

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.

Categories

Resources