Receive emails from gmail

1

How can you receive Gmail emails from Python?

#Ya logra conectar con gmail.
import smtplib, getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

print("email con Gmail")
usuario = input("Cuenta de gmail:")
contraseña = getpass.getpass("Contraseña:")

serverSMTP = smtplib.SMTP('smtp.gmail.com', 587)
serverSMTP.ehlo()
serverSMTP.starttls()
serverSMTP.ehlo()
serverSMTP.login(usuario, contraseña)
    
asked by Ronny Esquivel 04.05.2018 в 07:46
source

1 answer

0

As commented by @abulafia, instead of SMTP that is used to send emails, you must use POP3 or IMAP (the latter is preferable).

Example of use:

import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]', 'suclave')
mail.list()
# Out: Lista de "carpetas" también conocidas como etiquetas en gmail.
mail.select("inbox") # conectarse a la bandeja de entrada.

result, data = mail.search(None, "ALL")

ids = data[0] # los datos son una lista.
id_list = ids.split() # IDS es una cadena separada por espacios
latest_email_id = id_list[-1] # Obtén el ultimo

result, data = mail.fetch(latest_email_id, "(RFC822)") # buscar el cuerpo del correo electrónico (RFC822) para la identificación dada

raw_email = data[0][1] # Aquí está el cuerpo, que es el texto en bruto de todo el correo electrónico
# incluyendo encabezados y cargas útiles alternativas

Use the keyword "ALL" to get all the results (documented in RFC3501 ).

This code is not mine, I have taken it from the following link:

  

In addition to this I can suggest the use of two libraries (Translate from English):

  
    
answered by 04.05.2018 в 14:33