Sending email via gmail & python

前端 未结 7 677
走了就别回头了
走了就别回头了 2020-11-30 22:52

What is the recommended way of sending emails with gmail and python?

There are a lot of SO threads, but most are old and also smtp with username & password is n

7条回答
  •  时光说笑
    2020-11-30 23:02

    I was stuck with the same question some time ago.

    Before you read the code - please go to-https://developers.google.com/gmail/api/quickstart/python

    Also, When going to the site listed above, enable the Gmail API, so that the code can be used.

    I had to google a lot and modify the already existing google Gmail API code to find make it something like this :-

    from __future__ import print_function
    import pickle
    import os.path
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    from email.mime.text import MIMEText
    import base64
    
    subject = "Subject_Goes_Here"
    msg = "Your_Message_Text_Goes_Here"
    sender = "senders_email@email.com"
    receiver = "recievers_email@email.com"
    
    SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    message = MIMEText(msg)
    message['to'] = receiver
    message['from'] = sender
    message['subject'] = subject
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw' : raw}
    message = (service.users().messages().send(userId='me', body=body).execute())
    

    This code might seem long, but you only have to change the values in the variables, - subject , message , sender and receiver.

    I had modified the code according to my needs and it might not work for yours. Yet, there are many other examples online. For example, to make a mail with attachments, you can go here - https://developers.google.com/gmail/api/guides/uploads

    For this example, you have to downgrade your security, by enabling less-secure apps to access your Gmail account. But as this is a Google API, you need not worry. This code will also ask for your Gmail Password, but that is only as a security measure and is controlled and stored locally by the Google Servers.

    This code worked like a charm for me and I do hope that it does for you too.

    Thanks,

提交回复
热议问题