send email w/python

3096 ワード

simple email w/o attachement:
# 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.
textfile = "d:\\result.html"
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
me = "[email protected]"
you = "[email protected]"
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.live.com','587')
s.starttls() #    
s.login("[email protected]", "mima001")
s.sendmail(me, you, msg.as_string())
s.quit()

email w/html file:
import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "[email protected]"
you = "[email protected]"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative') #      
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
#text = "Hi!
How are you?
Here is the link you wanted:
http://www.python.org" #html = """\ #<html> # <head></head> # <body> # <p>Hi!<br> # How are you?<br> # Here is the <a href="http://www.python.org">link</a> you wanted. # </p> # </body> # #""" # Record the MIME types of both parts - text/plain and text/html. #part1 = MIMEText(text, 'plain') textfile = "d:\\result.html" fp = open(textfile, 'rb') part2 = MIMEText(fp.read(), 'plain') fp.close() part2.replace_header("Content-type", "Application/octet-stream;name='result.html'") # "Content-type" part2.add_header("Content-Disposition","attachment;filename='result.html'")# "Content-Disposition" "attachment" # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. #msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('smtp.live.com','587') s.starttls() s.login("[email protected]", "12345") # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit()

 
関連リンク:http://docs.python.org/library/email-examples.html