Python 3:通过任何在线webmail服务发送电子邮件

时间:2014-01-16 20:53:54

标签: email python-3.x webmail

什么样的python脚本/函数/库允许您通过任何webmail服务发送电子邮件,无论是gmail,yahoo,hotmail,来自您自己域名的电子邮件等等。

我找到了几个与单个案例(主要是gmail)相关的例子,但不是一个包罗万象的解决方案。

例如:用户输入用户名,密码,网络邮件服务,然后可以从python程序中发送电子邮件。

感谢。

2 个答案:

答案 0 :(得分:2)

嗯,你可以在这里看到一些如何做的例子:http://docs.python.org/3/library/email-examples.html

否则,你可以试试这个:

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

答案 1 :(得分:0)

您可以使用smtplib模块通过任何支持SMTP的网络邮件发送电子邮件。看起来像这样:

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

请注意,此示例既不干净也不经过测试。查看文档以获取更多信息。此外,您很可能需要根据要连接的服务器调整大量内容。

要创建消息,最好查看email模块。