0

什么是广泛使用的Python 3 Gmail实现,因此“允许安全性较低的应用程序”不是必需的?什么是广泛使用的Python 3 Gmail的实施,使“不允许安全的应用程序”谷歌设置不是必需的?

这里是(有些流行的)标准的Gmail,它需要设置实施了 “允许安全性较低的应用程序” 谷歌设置:

import smtplib 

# Catch Exceptions - smtplib.SMTPException 

    try: 
     mail = smtplib.SMTP("smtp.gmail.com", 587) 
     mail.ehlo() 
     mail.starttls() 
     mail.ehlo() 
     mail.login(str(source_email),str(source_password)) 
     mail.sendmail(str(source_email), str(destination_email), str(email_content)) 
     mail.close() 

    except smtplib.SMTPException: 
     print("ERROR, CAN NOT SEND MAIL - smtplib.SMTPException ... ") 

“””


注意:这些问题的答案我我正在寻找将涉及代码示例,实施此安全协议 - https://developers.google.com/gmail/imap/xoauth2-protocol

这里是谷歌网站的例子 - https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough


“””

我感谢所有的Python 3的应用程序的Gmail xoauth2协议的例子可以给你。

这也将是有帮助的Windows 10的Outlook电子邮件的Python 3应用程序的电子邮件实施的例子。

+0

我想补充一些链接,解释如何在Python 3应用程序实现的Gmail:(LINK#1) - https://developers.google.com/ gmail/api/guides/sending –

+0

我想添加几个链接来解释如何在Python 3应用程序中实现Gmail:(链接#2) - https://developers.google.com/gmail/api/v1/ reference/users/messages/send –

+0

我想添加几个链接来解释如何在Python 3应用程序中实现Gmail:(链接#3) - https://developers.google.com/gmail/api/guides/ –

回答

0

下面的代码示例演示如何创建一个MIME消息,编码到base64url串,并将其分配给该消息的资源的原始字段:

为电子邮件创建的消息。

参数数量: 发件人:发件人的电子邮件地址。 发送至:接收者的电子邮件地址。 主题:电子邮件的主题。 MESSAGE_TEXT:电子邮件消息的文本。 返回: 包含base64url编码电子邮件对象的对象。

def create_message(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())} 
0

创建带有附件

创建具有附件的消息的消息是像创建任何其他消息,但该文件上传作为多部分MIME消息的过程依赖于编程语言。以下代码示例演示了使用附件创建多部分MIME消息的可能方式。

前面的例子相似,该实施例还处理进行编码以base64url消息并将其分配给该消息的资源的原始场。

为电子邮件创建的消息。

参数数量: 发件人:发件人的电子邮件地址。 到:接收机电子邮件地址。 主题:电子邮件的主题。 MESSAGE_TEXT:电子邮件消息的文本。 file:要附加文件的路径。

返回: 一个包含base64url编码电子邮件对象的对象。

def create_message_with_attachment(
    sender, to, subject, message_text, file): 
    message = MIMEMultipart() 
    message['to'] = to 
    message['from'] = sender 
    message['subject'] = subject 

    msg = MIMEText(message_text) 
    message.attach(msg) 

    content_type, encoding = mimetypes.guess_type(file) 

    if content_type is None or encoding is not None: 
     content_type = 'application/octet-stream' 
     main_type, sub_type = content_type.split('/', 1) 
    if main_type == 'text': 
     fp = open(file, 'rb') 
     msg = MIMEText(fp.read(), _subtype=sub_type) 
     fp.close() 
    elif main_type == 'image': 
     fp = open(file, 'rb') 
     msg = MIMEImage(fp.read(), _subtype=sub_type) 
     fp.close() 
    elif main_type == 'audio': 
     fp = open(file, 'rb') 
     msg = MIMEAudio(fp.read(), _subtype=sub_type) 
     fp.close() 
    else: 
     fp = open(file, 'rb') 
     msg = MIMEBase(main_type, sub_type) 
     msg.set_payload(fp.read()) 
     fp.close() 
    filename = os.path.basename(file) 
    msg.add_header('Content-Disposition', 'attachment', filename=filename) 
    message.attach(msg) 

    return {'raw': base64.urlsafe_b64encode(message.as_string())} 
0

发送消息

一旦创建的消息,则可以通过在呼叫的请求体供给它messages.send,如在下面的例子证明发送。

发送电子邮件。

参数数量: 服务:授权的Gmail API服务实例。 user_id:用户的电子邮件地址。特殊值“我”可用于指示已认证的用户。 消息:要发送的消息。

返回: 发送消息。

def send_message(service, user_id, 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 
0

这里是一个类似的例子组合所有部分:

"""Send an email message from the user's account. 
""" 

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 
import os 

from apiclient import errors 


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 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 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())} 


def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir, 
          filename): 
    """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. 
     file_dir: The directory containing the file to be attached. 
     filename: The name of the file to be attached. 

    Returns: 
     An object containing a base64url encoded email object. 
    """ 
    message = MIMEMultipart() 
    message['to'] = to 
    message['from'] = sender 
    message['subject'] = subject 

    msg = MIMEText(message_text) 
    message.attach(msg) 

    path = os.path.join(file_dir, filename) 
    content_type, encoding = mimetypes.guess_type(path) 

    if content_type is None or encoding is not None: 
    content_type = 'application/octet-stream' 
    main_type, sub_type = content_type.split('/', 1) 
    if main_type == 'text': 
    fp = open(path, 'rb') 
    msg = MIMEText(fp.read(), _subtype=sub_type) 
    fp.close() 
    elif main_type == 'image': 
    fp = open(path, 'rb') 
    msg = MIMEImage(fp.read(), _subtype=sub_type) 
    fp.close() 
    elif main_type == 'audio': 
    fp = open(path, 'rb') 
    msg = MIMEAudio(fp.read(), _subtype=sub_type) 
    fp.close() 
    else: 
    fp = open(path, 'rb') 
    msg = MIMEBase(main_type, sub_type) 
    msg.set_payload(fp.read()) 
    fp.close() 

    msg.add_header('Content-Disposition', 'attachment', filename=filename) 
    message.attach(msg) 

    return {'raw': base64.urlsafe_b64encode(message.as_string())} 
0

PYTHON 3 CODE表示抵达GMAIL API客户机凭证:

“”” 程序:get_credentials_PYTHON3.py

描述:

创建Gmail API s gmail发送范围的服务对象。运行此 get_credentials_PYTHON3.py创建用于Gmail发送范围的JSON文件。

请注意,CM-CLIENT-1是以下客户端名称,您将更改 以对应于您在设置 项目的oauth2client NAME时创建的客户端名称以获取凭证。

语言:Python的3.6.2 “” “

from __future__ import print_function 
import httplib2 
import os 

from apiclient import discovery 
from oauth2client import client 
from oauth2client import tools 
from oauth2client.file import Storage 

try: 
    import argparse 
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 
except ImportError: 
    flags = None 

”“” 如果修改这些范围,删除在路径.... HOME_DIR.credentials.gmail的Python创建您以前保存的凭证 -quickstart.json

重新:SCOPES = 'https://www.googleapis.com/auth/gmail.send'

重新:APPLICATION_NAME = 'CM-CLIENT-1'

“””

SCOPES = 'https://www.googleapis.com/auth/gmail.send' 
    CLIENT_SECRET_FILE = 'client_secret.json' 
    APPLICATION_NAME = 'CM-CLIENT-1' 


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 = 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 

def main(): 
    """Shows basic usage of the Gmail API. 

    Creates a Gmail API service object for gmail send scope. 

    Running this Creates JSON File used for Gmail send scope. 
    """ 
    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    service = discovery.build('gmail', 'v1', http=http) 


if __name__ == '__main__': 
    main() 
0

发送的Gmail .... Python的3.6。2

说明:将以前收到的凭证 作为GMAIL API客户端发送。

从用户的帐户发送电子邮件消息。 我的Gmail API客户端名称是CM-CIENT-1 这,CM_CLIENT-1是服务: oauth2授权的Gmail API服务实例。 语言:Python的3.6.2

from __future__ import print_function 
import httplib2 
import os 

from apiclient import discovery 
from oauth2client import client 
from oauth2client import tools 
from oauth2client.file import Storage 

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 
import os 
from apiclient import errors 

try: 
    import argparse 
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 
except ImportError: 
    flags = None 

SCOPES = 'https://www.googleapis.com/auth/gmail.send' 
CLIENT_SECRET_FILE = 'client_secret.json' 
APPLICATION_NAME = 'CM-CLIENT-1' 

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 = 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 


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: ' + str(message['id'])) 
     return message 
     except Exception as ex: 
     print("..... An error occurred while executing ...... SendMessage .......") 
     print(ex) 


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()} 


def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir, filename): 
     """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. 
    file_dir: The directory containing the file to be attached. 
    filename: The name of the file to be attached. 

    Returns: 
    An object containing a base64url encoded email object. 
    """ 

     message = MIMEMultipart() 
     message['to'] = to 
     message['from'] = sender 
     message['subject'] = subject 

     msg = MIMEText(message_text) 
     message.attach(msg) 

     path = os.path.join(file_dir, filename) 
     content_type, encoding = mimetypes.guess_type(path) 

     if content_type is None or encoding is not None: 
      content_type = 'application/octet-stream' 
      main_type, sub_type = content_type.split('/', 1) 
     if main_type == 'text': 
      fp = open(path, 'rb') 
      msg = MIMEText(fp.read(), _subtype=sub_type) 
      fp.close() 
     elif main_type == 'image': 
      fp = open(path, 'rb') 
      msg = MIMEImage(fp.read(), _subtype=sub_type) 
      fp.close() 
     elif main_type == 'audio': 
      fp = open(path, 'rb') 
      msg = MIMEAudio(fp.read(), _subtype=sub_type) 
      fp.close() 
     else: 
      fp = open(path, 'rb') 
      msg = MIMEBase(main_type, sub_type) 
      msg.set_payload(fp.read()) 
      fp.close() 

     msg.add_header('Content-Disposition', 'attachment', filename=filename) 
    message.attach(msg) 

     return {'raw': base64.urlsafe_b64encode(message.as_string())} 



def main(): 

     try: 

      credentials = get_credentials() 
      http = credentials.authorize(httplib2.Http()) 
      service = discovery.build('gmail', 'v1', http=http) 

      # Send Gmail Message 

      SendMessage(service, "me", CreateMessage("[email protected]", 
"[email protected]", "Test Gmail Automation", "GMAIL SENT FROM APP")) 

     except Exception as e: 
      print ("ERROR !! - The Error is ..... " + str(e)) 
      raise 


if __name__ == '__main__': 
    main() 
相关问题