Вопрос

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.

Это было полезно?

Решение

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 = 'your_address@email.com'

    # 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: 'your_address@email.com'.
        #            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()

Другие советы

You can send E-Mails via any webmail (that supports SMTP) with the smtplib module. That looks like this:

import smtplib
import getpass

servername = input("Please enter you mail server: ")
username = input("Please enter your username: ")
password = getpass.getpass() # This gets the password without echoing it on the screen
server = smtplib.SMTP(servername)
server.login(username, password)  # Caution this now uses plain connections
                                  # Read the documentations to see how to use SSL
to = input("Enter your destination address: ")
msg = input("Enter message: ")
message = "From: {0}@{1}\r\nTo: {2}\r\n\r\n{3}".format(username, servername, to, msg)
server.sendmail(username+"@"+servername, to, message)
server.quit

Please note that this example is neither clean nor tested. Look at the documentation for more information. Also it is very likely that you need to adjust a lot of stuff depending on the server you want to connect with.

For creating the message it's a good idea to look at the email module.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top