用Python发送邮件
可能重复的问题:
在Python中接收和发送电子邮件
我试着搜索过,但找不到简单的方法来发送电子邮件。
我想要的东西大概是这样的:
from:"Test1@test.com"#email sender
To:"test2@test.com"# my email
content:open('x.txt','r')
我找到的所有方法都太复杂了:我的项目不需要这么多代码。
请帮帮我,我想学习:在每段代码里加上注释并解释一下。
3 个回答
0
这是一个简单的例子,使用了 smtplib,对我来说可以正常工作:
#!/usr/bin/env python
import smtplib # Brings in the smtp library
smtpServer='smtp.yourdomain.com' # Set the server - change for your needs
fromAddr='you@yourAddress' # Set the from address - change for your needs
toAddr='you@yourAddress' # Set the to address - change for your needs
# In the lines below the subject and message text get set up
text='''Subject: Python send mail test
Hey!
This is a test of sending email from within Python.
Yourself!
'''
server = smtplib.SMTP(smtpServer) # Instantiate server object, making connection
server.set_debuglevel(1) # Turn debugging on to get problem messages
server.sendmail(fromAddr, toAddr, text) # sends the message
server.quit() # you're done
这段代码是我之前在 这个链接 找到的,然后我做了一些修改。
1
在编程中,有时候我们会遇到一些问题,想要找到解决办法。比如说,某个功能不工作,或者程序运行得很慢。这时候,我们可以去一个叫StackOverflow的网站上寻求帮助。这个网站上有很多程序员分享他们的经验和解决方案。
当你在这个网站上提问时,最好把问题描述得清楚明了。比如,你可以告诉大家你在做什么,遇到了什么具体的问题,程序是怎么运行的,甚至可以把相关的代码贴上来。这样其他人才能更好地理解你的问题,并给出有效的建议。
总之,StackOverflow是一个很好的资源,可以帮助你解决编程中遇到的各种问题。只要你能清楚地表达自己的疑问,就能得到其他人的帮助。
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
8
这个文档写得很简单明了:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.sendmail(me, [you], msg.as_string())
s.quit()