title: Send mail in Gmail with python
body: <p>I'm trying to send a simple test email using the Gmail API but I keep getting the same error for every code sample I find.</p>
  
  <p>My code at the moment is this:</p>
  
  <pre><code>def validationService():
      SCOPES = ['https://mail.google.com/']
      SERVICE_ACCOUNT_FILE = 'creds.json'
      creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
  
      service = build('gmail', 'v1', credentials=creds)
      return service
  
  
  def SendMessage(service, user_id, message):
    try:
      message = (service.users().messages().send(userId=user_id, body=message).execute())
      print('Message Id:',message['id'])
      return message
    except errors.HttpError as error:
      print('An error occurred:', error)
  
  
  def CreateMessage(sender, to, subject, message_text):
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
  
  service = validationService()
  
  email = CreateMessage("sendermail@gmail.com", "receiverrmail@gmail.com", "Test", "This is a test")
  
  sent = SendMessage(service, "sendermail@gmail.com", email)
  </code></pre>
  
  <p>Returns</p>
  
  <pre><code>&gt;&gt;&gt; An error occurred: &lt;HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Bad Request"&gt;
  </code></pre>
  
  <p>I also don't understand the difference between the "sender" parameter at CreateMessage and userId at SendMessage.</p>
  
  <p>If serves a purpose, I'm using a Service Account credential</p>
  
  <p>-
  Thanks!</p>