How to change name of Sender in Python Gmail API? - python

I am working on a script that emails me when I get new grades blah blah. Everything works perfectly except that the sender shows up as my email...
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from email.mime.text import MIMEText
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().encode("utf-8")).decode()}
def send_message(message):
global service
user_id = "me"
"""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())
return message
except exception as error: # I am aware this line is broken, but it does goes through successfully so this does not execute
print('An error occurred: %s' % error)
# Setup the Gmail API
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid or creds == "None":
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
msg = create_message("fname lname", "to#email.com", '', content)
send_message(msg)
That is my code for sending a message, yet my email shows up as the sender when I send a message... How do I fix this?
(I have already tried setting the sender as "John Smith" <from#email.com> and John Smith <from#email.com>)

I just got it working in ruby by setting the mail option:
from: "'some name' <#{variable_of_email_string}>"

Use the following code:
sender = 'John Smith <from#email.com>'
receiver = 'sample#email.com'
subject = 'Subject'
message_text = 'Example of message'
message = create_message(sender, receiver, subject, message_text)

Related

Unable to send email python: ValueError: Authorized user info was not in the expected format, missing fields client_secret, client_id, refresh_token

I want to send email from my python code to gmail using oAuth2. For that I have created the project using google api and generated the secrets token.
I am not sure how to use that in my code. Any help would be appreciated.
Below is my python code:
import smtplib, json
from email.mime.text import MIMEText
from google.oauth2.credentials import Credentials
class EmailSender:
def __init__(self, credentials):
self.credentials = credentials
def send_email(self, to, subject, body):
try:
# Create the email message
msg = MIMEText(body)
msg['to'] = to
msg['subject'] = subject
msg['from'] = self.credentials.email
# Send the email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(self.credentials.email, self.credentials.token)
server.send_message(msg)
print("Email sent!")
except Exception as e:
print("Error: ", e)
finally:
server.quit()
with open("OAuth2_credential_secret.json", 'r') as stream:
creds_json = json.load(stream)
creds = Credentials.from_authorized_user_info(creds_json)
sender = EmailSender(creds)
sender.send_email("xxx#gmail.com", "Hello", "Hello World!")

Reply to email using imap email object

I have an email object of an unread email. How do I reply to the email using SMTP lib using the specific email object i.e. (if mail comes from flipkart, the particular mail has an object. I want to reply using that mail object)? I tried using msg['Reply_To'] and I got an error saying the email id is not valid. I did check the smtp documentation and couldn't find anything regarding the same. Here when I comment the [send to] and only add [reply to] the error is shown below. But when I uncomment the same the mail is sent but it is not sent as a reply. This shows that the email id is correct.
CODE:
def SendReply(self):
self.msg["from"] = self.From
self.msg["Cc"] = self.cc
self.msg["To"] = self.To
self.msg["Subject"] = self.Subject
self.Body = str(self.Body)
self.msg["Reply_To"] = self.Reply_To
self.msg.set_content(self.Body)
# print("Print this now", self.msg["Reply_To"])
if self.Attachments is not None:
with open(self.Attachments, "rb") as f:
file_data = f.read()
self.msg.add_attachment(
file_data,
maintype="application",
subtype="xlsx",
filename=self.Attachments,
)
with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
smtp.starttls()
smtp.login(self.From, self.EmailPassword)
self.msg["Reply_To"] = self.Reply_To
smtp.send_message(self.msg)
return ("Mail sent Succesfully", True)
ERROR:
smtplib.SMTPRecipientsRefused:
{'None': (553,
b'5.1.3 The recipient address <None> is not a valid RFC-5321 address.
Learn\n5.1.3 more at\n5.1.3 https://support.google.com/mail/answer/6596 ij25-20020a170902ab5900b0016beceac426sm3191763plb.138 - gsmtp')}

How to get a API with email

I'm trying to figure out how to email a person with python and I'm wondering on how to get the api-key.
from socketlabs.injectionapi import SocketLabsClient
from socketlabs.injectionapi.message.bulkmessage import BulkMessage
from socketlabs.injectionapi.message.bulkrecipient import BulkRecipient
from socketlabs.injectionapi.message.emailaddress import EmailAddress
# Your SocketLabs ServerId and Injection API key
client = SocketLabsClient(10000, "YOUR-API-KEY");
message = BulkMessage()
message.plain_text_body = "This is the body of my message sent to %%Name%%"
message.html_body = "<html>This is the HtmlBody of my message sent to %%Name%%</html>"
message.subject = "Sending a test message"
message.from_email_address = EmailAddress("from#example.com")
can someone tell me how to get a api-key or what it is?
I Know How to send emails with Python i can help you with that
import smtplib
import socket
email='Your Email Address'
password='Your Password'
def sendMail(to, message):
#you can replace gmail with type of email you use(outlook, yahoo, etc) but port number(587) is same
try:
server=smtplib.SMTP('smtp.gmail.com', 587)
except socket.gaierror:
print('No Internet')
server.ehlo()
server.starttls()
# if ur login account is gmail then please turn on lesssecure app access at myaccount.google.com/lesssecureapps
server.login(email, password)
server.sendmail('Your Email', to, message)
sendMail('example#outlook.com', 'message')
You have to sign up to socketlabs. Then only you will get an API key for sending the automated email.

Can't save new message to Drafts in gmail

I am trying to create and save message to Drafts in gmail, but nothing happen.
import time
import random
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import imaplib
def save_draft(email_to, body, login, password, image):
msg = MIMEMultipart("alternative")
msg.set_charset("utf-8")
msg.attach(MIMEText(body, "plain", "utf-8"))
msg['Subject'] = SUBJECT
msg['From'] = login
msg['To'] = email_to
with open(image, 'rb') as f:
part = MIMEApplication(
f.read(),
Name=image
)
part['Content-Disposition'] = 'attachment; filename={}'.format(IMAGE)
msg.attach(part)
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(login, password)
imap.select('[Gmail]/Drafts')
now = imaplib.Time2Internaldate(time.time())
imap.append('[Gmail]/Drafts',
'',
now,
msg.as_bytes())
imap.logout()
When I am changing msg.as_bytes() to msg.as_string(), I got the error below:
TypeError: cannot use a bytes pattern on a string-like object
If you are using Python library here is the code snippet:
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())}
Once you have created a Message object, you can pass it to the drafts.create method to create a Draft object.
def create_draft(service, user_id, message_body):
"""Create and insert a draft email. Print the returned draft's message and id.
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_body: The body of the email message, including headers.
Returns:
Draft object, including draft id and message meta data.
"""
try:
message = {'message': message_body}
draft = service.users().drafts().create(userId=user_id, body=message).execute()
print 'Draft id: %s\nDraft message: %s' % (draft['id'], draft['message'])
return draft
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
Also, here is a related SO post that stated: you have decode the bytes object to produce a string.
Hope this helps.

Python Email, [Errno 10061] No connection could be made because the target machine actively refused it

I want to send a mail in using python, below is my code, but I got the error 10061 at the end, hope anyone can help me, thanks!
import smtplib
fromaddr = 'XXX#XX.com'
toaddrs = 'XXX#XX.com '
msg = 'Why,Oh why!'
username = 'XXXXXX'
password = 'XXXXXX'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
error msg:socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
As mentioned by Cid-EL, You have to enable less secure apps in GMAIL settings
However, It's not secure to turn on that perticular option.
Gmail provides API's to perform mail operations. GMAIL API's are supported in many languages.
For Python API : Python with Gmail
For Java API's : Java with Gmail
Little more effort but you can have a secure connection !!
Step 1: Turn on the GMAIL API
Step 2: Install Google client library
pip install --upgrade google-api-python-client
Step 3: Code sample to send a mail using GMAIL API
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
SCOPES = "https://mail.google.com/"
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python 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-python-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 compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
# create a message
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
return {'raw': base64.b64encode(message.as_string())}
#send message
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, error:
print ('An error occurred: %s' % error)
def main():
"""Shows basic usage of the Gmail API.
Send a mail using gmail API
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
msg_body = "test message"
message = CreateMessage("xxxxx#gmail.com", "yyy#gmail.com", "Status report of opened tickets", msg_body)
SendMessage(service, "me", message)
if __name__ == '__main__':
main()
As far as I know Gmail and other companies have security to prevent emails being sent from unknown sources, but this link can turn that kind of security off.
There you can modify the account so it will accept the email.
I use this code to send email:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_address = 'johndoe#gmail.com'
to_address = 'johndoe#gmail.com'
message = MIMEMultipart('Foobar')
epos_liggaam['Subject'] = 'Foobar'
message['From'] = from_address
message['To'] = to_address
content = MIMEText('Some message content', 'plain')
message.attach(content)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login(from_address, 'password')
mail.sendmail(from_address,to_address, message.as_string())
mail.close()

Categories