How to send an image by gmail 2022 - python-3.x

I have a python script that detects motion in teh camera and then sends an email to the supplied email.
The issue is that Gmail has changed the way it allows apps to send external emails.
How can I change my code to properly send an email with an attached image?
Here is my code:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# Email you want to send the update from (only works with gmail)
fromEmail = 'some_email#gmail.com'
# You can generate an app password here to avoid storing your password in plain text
# https://support.google.com/accounts/answer/185833?hl=en
fromEmailPassword = 'somepassword'
# Email you want to send the update to
toEmail = 'some_email#gmail.com'
smtp_port = 587 # Standard secure SMTP port
smtp_server = "smtp.gmail.com" # Google SMTP Server
TIE_server = smtplib.SMTP(smtp_server, smtp_port)
def sendEmail(image):
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Security Update'
msgRoot['From'] = fromEmail
msgRoot['To'] = toEmail
msgRoot.preamble = 'camera update'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('Smart security cam found object')
msgAlternative.attach(msgText)
msgText = MIMEText('<img src="cid:image1">', 'html')
msgAlternative.attach(msgText)
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
zsmtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(fromEmail, fromEmailPassword)
smtp.sendmail(fromEmail, toEmail, msgRoot.as_string())
smtp.quit()
Thanks.

Related

Sending email via smtp only works if sender and recipient are the same v.v

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
user = 'user#icloud.com'
password = 'apppassword'
host = 'smtp.mail.me.com'
text = 'E-Mail Body'
subject = 'This is a Subject'
to_emails = ['user2#icloud.com']
from_email = 'John Doe <user#icloud.com>'
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = 'user2#icloud.com'
msg['Subject'] = subject
body = MIMEText(text, 'plain')
msg.attach(body)
msg_str = msg.as_string()
server = smtplib.SMTP(host, port=587)
server.starttls()
server.ehlo()
server.login(user, password)
server.sendmail(from_email, to_emails, msg_str)
server.quit()
I am trying to program an email client in python.
At the moment I fail to send via iCloud.
The email only arrives if I send the email to the iCloud mail that sends it. So to myself.
So you could say it's the loneliest email client in the world right now.
But all kidding aside, I don't get it. Is it me? Is it iCloud?

How do I avoid accumulating gmails with the same subject using SMTPLIB and Python

When I send files with the same subject using the code the emails accumulate in the inbox.
What I want to do is that these do not accumulate and are sent one by one with the same subject.
from email.mime.text import MIMEText
import smtplib
import smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
receiver = 'receiver'
sender = 'sender'
senders_password = 'password_application_sender'#This password is a password of application, this option activate in manager account of his gmail account
file = "path of file"
subject = 'subject' #This subject always is the same
mensaje = MIMEMultipart("alternative")
mensaje["Subject"] = subject
mensaje["From"] = sender
mensaje["To"] = receiver
html = f"""
<html>
<body>
Hi this is a email with a attachment
</body>
</html>
"""
body_html = MIMEText(html, "html")
mensaje.attach(body_html)
with open(file, "rb") as attachment:
content = MIMEBase("application","octet-stream")
content.set_payload(attachment.read())
encoders.encode_base64(content)
content.add_header(
"Content-Disposition",
f"attachment; filename= {file}",
)
mensaje.attach(content)
text = mensaje.as_string()
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender, senders_password)
server.sendmail(sender, receiver, text)
server.quit()
print("Email Send")
How I receive the email and How should it get

I am trying to send a gmail text to someone

so I tried to send it gave me this error
here is the error
Traceback (most recent call last):
File "C:\Users\23470\AppData\Local\Programs\Python\Python39\mess.py", line 6, in <module>
server = smtplib.SMTP(smtpServer,25)
File "C:\Users\23470\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 258, in __init__
raise SMTPConnectError(code, msg)
smtplib.SMTPConnectError: (451, b'Request action aborted on MFE proxy, SMTP server is not
available.')
Here is my code
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='imranalubankudi#gmail.com'
toAddr='gmmeremnwanne#gmail.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer,25)
server = smtplib.SMTP(smtpServer,25)
server.ehlo()
server.starttls()
server.sendmail(fromAddr, toAddr, text)
server.quit()
Try changing port to 587. Also your smtpServer don't looks right for gmail.
server = smtplib.SMTP('smtp.gmail.com', 587)
You should also need to login to session.
Here's a simple function that sends a simple text mail through gmail.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(send_from, send_to, subject, body):
#The mail addresses and password
sender_pass = 'your_gmail_password'
#Setup the MIME
message = MIMEMultipart()
message['From'] = send_from
message['To'] = send_to
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(send_from, sender_pass)
text = message.as_string()
session.sendmail(send_from, send_to, text)
session.quit()

Sending a gmail message

im trying to send a gmail message with the following code:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
#return {'raw': base64.urlsafe_b64encode(message.as_string())}
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
#body = {'raw': b64_string}
return {'raw': b64_string}
s = "email"
t = "email"
sub = "test subject"
m = "message test"
create_message(s,t,sub,m)
where s = my email(replaced with "email" in this example and t = my other email (again replaced))
It doesnt kick out any errors but doesnt send the message.
Also this code didnt work:
#return {'raw': base64.urlsafe_b64encode(message.as_string())}
as it produced the following error: TypeError: a bytes-like object is required, not 'str'
"I solved that" with this:
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
#body = {'raw': b64_string}
return {'raw': b64_string}
edit(1): I do have credentials.json and passed the google api example
Needed to create client_secret.json and paste my credentials there, ctrc+c, ctrl+v an old example and update it to python 3.x, resolved base 64 issue and it works :)
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from oauth2client import file
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://mail.google.com/'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatability with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
import base64
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
import mimetypes
from httplib2 import Http
from apiclient import errors
from apiclient.discovery import build
credentials = get_credentials()
service = build('gmail', 'v1', http=credentials.authorize(Http()))
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
def CreateMessage(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64 encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
#body = {'raw': b64_string}
return {'raw': b64_string}
#return {'raw': base64.b64encode(message.as_string())}
testMessage = CreateMessage("email","email","test_subject","test_message")
testSend = SendMessage(service, 'me', testMessage)
emails replaced with email in line 106 (second from bottom)

Not able to send the mail without password authentication in python

I am not able to send the mail without password authentication in python.Its printing the last message but mail is not sent.Below is the code that i am using.Anyone please help i am stuck because of this. Thanks in advance.
import smtplib
fromaddr = 'xyz#gmail.com'
toaddrs = ['abc#gmail.com']
msg = '''
From: {fromaddr}
To: {toaddr}
Subject: 'testing'
This is a test
.
'''
msg = msg.format(fromaddr =fromaddr, toaddr = toaddrs[0])
server = smtplib.SMTP("gmail-smtp-in.l.google.com:25")
server.starttls()
server.ehlo("example.com")
server.mail(fromaddr)
server.rcpt(toaddrs[0])
server.data(msg)
server.quit/close()
print("mail sent")

Resources