Search code examples
emailpython-3.xwebmail

Python 3: sending emails through any online webmail service


what sort of python script/function/library would allow you to send emails through any webmail service, be it gmail, yahoo, hotmail, email from your own domain etc.?

I found several examples relating to the single cases (mostly gmail), but not an all-encompassing solution.

Ex.: user inputs username, password, webmail service, then can send an email from within the python program.

Thanks.


Solution

  • Well, you can see some examples of how to do it here: http://docs.python.org/3/library/email-examples.html

    Otherwise, you can try this:

    from smtplib import SMTP_SSL as SMTP
    import logging, logging.handlers, sys
    from email.mime.text import MIMEText
    
    def send_message():
        text = '''
                Hello,
    
                This is an example of how to use email in Python 3.
    
                Sincerely,
    
                My name
                '''        
        message = MIMEText(text, 'plain')
        message['Subject'] = "Email Subject" 
        my_email = '[email protected]'
    
        # Email that you want to send a message
        message['To'] = my_email
    
        try:
            # You need to change here, depending on the email that you use.
            # For example, Gmail and Yahoo have different smtp. You need to know what it is.
            connection = SMTP('smtp.email.com')
            connection.set_debuglevel(True)
    
            # Attention: You can't put for example: '[email protected]'.
            #            You need to put only the address. In this case, 'your_address'.
            connection.login('your_address', 'your_password')
    
            try:
                #sendemail(<from address>, <to address>, <message>)
                connection.sendmail(my_email, my_email, message.as_string())
            finally:
                connection.close()
        except Exception as exc:
            logger.error("Error sending the message.")
            logger.critical(exc)
            sys.exit("Failure: {}".format(exc))
    
    if __name__ == "__main__":
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        logger.addHandler(ch)
    
        send_message()