2012-07-09 21 views
0

请帮帮我!我想在python 3中创建一个脚本,它将电子邮件发送给任何人,但是从本地机器发送。我现在是python的初学者,这就是为什么我尝试过的大多数脚本根本不起作用。如果你还解释了我需要做的脚本,这将是一个很大的帮助。谢谢!如何使用python 3发送电子邮件?

+4

[你尝试过什么?](http://whathaveyoutried.com/) – thegrinner 2012-07-09 14:15:04

+0

如果一个初学者,你有一本书或教程学习的榜样 - 因为这些展示和解释工作代码 – Mark 2012-07-09 14:16:36

+2

的http://文档.python.org/dev/library/email-examples.html – jfs 2012-07-09 14:35:14

回答

5

怎么样这短短数少。

''' 
Created on Jul 10, 2012 
test email message 
@author: user352472 
''' 
from smtplib import SMTP_SSL as SMTP 
import logging 
import logging.handlers 
import sys 
from email.mime.text import MIMEText 

def send_confirmation(): 
    text = ''' 
    Hello, 

    Here is your test email. 

    Cheers! 
    '''   
    msg = MIMEText(text, 'plain') 
    msg['Subject'] = "test email" 
    me ='[email protected]' 
    msg['To'] = me 
    try: 
     conn = SMTP('smtp.email.com') 
     conn.set_debuglevel(True) 
     conn.login('yourcooladdress', 'yoursophisticatedpassword') 
     try: 
      conn.sendmail(me, me, msg.as_string()) 
     finally: 
      conn.close() 

    except Exception as exc: 
     logger.error("ERROR!!!") 
     logger.critical(exc) 
     sys.exit("Mail failed: {}".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) 

    random_ass_condition = True 

    if random_ass_condition: 
     send_confirmation() 
+0

...哇。记录是否真的有必要? – Dubslow 2012-07-10 09:49:09

+0

可能不是。我无耻地从一个项目中使用这个代码,它拥有更多的功能,并且日志记录派上用场。我想你可以把它拉出来,但我选择在它可以重新使用的情况下离开它。 – user352472 2012-07-10 11:25:45

+1

我可以在30分钟内整理出更有用的课程,并从上面链接的例子中获得帮助。但是,OP不会学到任何东西...... – Dubslow 2012-07-10 11:32:48

相关问题