使用python中的yahoo帐户发送电子邮件

时间:2013-05-05 04:53:06

标签: python email smtp

我有yahoo帐号。 是否有任何python代码可以从我的帐户发送电子邮件?

5 个答案:

答案 0 :(得分:12)

是的;这是代码:

import smtplib
fromMy = 'yourMail@yahoo.com' # fun-fact: from is a keyword in python, you can't use it as variable, did abyone check if this code even works?
to  = 'SomeOne@Example.com'
subj='TheSubject'
date='2/1/2010'
message_text='Hello Or any thing you want to send'

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( fromMy, to, subj, date, message_text )

username = str('yourMail@yahoo.com')  
password = str('yourPassWord')  

try :
    server = smtplib.SMTP("smtp.mail.yahoo.com",587)
    server.login(username,password)
    server.sendmail(fromMy, to,msg)
    server.quit()    
    print 'ok the email has sent '
except :
    print 'can\'t send the Email'

答案 1 :(得分:5)

关于使用雅虎的smtp服务器,我(简要地)摇了摇头。 465就行不通。我决定通过587端口的TLS路由,我能够验证并发送电子邮件。

import smtplib
from email.mime.text import MIMEText
SMTP_SERVER = "smtp.mail.yahoo.com"
SMTP_PORT = 587
SMTP_USERNAME = "username"
SMTP_PASSWORD = "password"
EMAIL_FROM = "fromaddress@yahoo.com"
EMAIL_TO = "toaddress@gmail.com"
EMAIL_SUBJECT = "REMINDER:"
co_msg = """
Hello, [username]! Just wanted to send a friendly appointment
reminder for your appointment:
[Company]
Where: [companyAddress]
Time: [appointmentTime]
Company URL: [companyUrl]
Change appointment?? Add Service??
change notification preference (text msg/email)
"""
def send_email():
    msg = MIMEText(co_msg)
    msg['Subject'] = EMAIL_SUBJECT + "Company - Service at appointmentTime"
    msg['From'] = EMAIL_FROM 
    msg['To'] = EMAIL_TO
    debuglevel = True
    mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    mail.set_debuglevel(debuglevel)
    mail.starttls()
    mail.login(SMTP_USERNAME, SMTP_PASSWORD)
    mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
    mail.quit()

if __name__=='__main__':
send_email()

答案 2 :(得分:3)

支持非ascii字符;你可以使用email package

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header    import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL

# provide credentials
login = 'you@yahoo.com'
password = getpass('Password for "%s": ' % login)

# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ', '.join([login, ])

# send it   
s = SMTP_SSL('smtp.mail.yahoo.com', timeout=10) #NOTE: no server cert. check
s.set_debuglevel(0)
try:
    s.login(login, password)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
    s.quit()

答案 3 :(得分:0)

访问Yahoo帐户安全页面here

您需要生成一个应用密码-这是屏幕底部的选项。在脚本中使用此页面上生成的Yahoo密码。

答案 4 :(得分:0)

有几个问题。已经发布的答案解决了其中一个问题。

  1. 使用 TLS(端口 465)
  2. 确保您有应用密码。雅虎和其他电子邮件服务已经更新了他们的身份验证实践,以限制可以在没有 2 因素身份验证的情况下登录的内容。如果您想使用 smtplib 进行身份验证,则需要在此处创建应用密码:https://login.yahoo.com/myaccount/security/app-password

如果你这样做,那么你就可以发送电子邮件