我第一次尝试Python编程是发送电子邮件的脚本。这是我计划在将来的应用程序中使用的东西,因此我认为这是一个很好的第一步。
发送纯文本电子邮件
下面显示的第一个脚本将基本的纯文本电子邮件发送到指定的电子邮件地址。您需要输入SMTP服务器的详细信息:
# Import smtplib to provide email functions import smtplib # Import the email modules from email.mime.text import MIMEText # Define email addresses to use addr_to = '[email protected]' addr_from = '[email protected]' # Define SMTP email server details smtp_server = 'mail.example.com' smtp_user = '[email protected]' smtp_pass = '1234567889' # Construct email msg = MIMEText('This is a test email') msg['To'] = addr_to msg['From'] = addr_from msg['Subject'] = 'Test 电子邮件 From RPi' # Send the message via an SMTP server try: s = smtplib.SMTP(smtp_server) s.login(smtp_user,smtp_pass) s.sendmail(addr_from, addr_to, msg.as_string()) s.quit() except: print("There was an error sending the email. Check the smtp settings.")
可以使用以下命令从命令行运行:
蟒蛇 send_email_text.py
要么 :
蟒蛇3 send_email_text.py
您可以使用以下命令将此脚本直接下载到您的Pi:
wget //bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/send_email_text.py
发送HTML电子邮件
下面的脚本是相似的,但是它发送HTML格式的电子邮件。您还可以指定无法读取HTML版本的电子邮件客户端读取的纯文本。
# Import smtplib to provide email functions import smtplib # Import the email modules from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Define email addresses to use addr_to = '[email protected]' addr_from = '[email protected]' # Define SMTP email server details smtp_server = 'mail.example.com' smtp_user = '[email protected]' smtp_pass = '1234567889' # Construct email msg = MIMEMultipart('alternative') msg['To'] = addr_to msg['From'] = addr_from msg['Subject'] = 'Test 电子邮件 From RPi' # Create the body of the message (a plain-text and an HTML version). text = "This is a test message.\nText and html." html = """\ <html> <head></head> <body> <p>This is a test message.</p> <p>Text and HTML</p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # 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 an SMTP server try: s = smtplib.SMTP(smtp_server) s.login(smtp_user,smtp_pass) s.sendmail(addr_from, addr_to, msg.as_string()) s.quit() except: print("There was an error sending the email. Check the smtp settings.")
该脚本构造了一个多部分的消息,其中每个部分都包含该消息的纯文本或HTML版本。
您可以使用以下命令将此脚本直接下载到您的Pi:
wget //bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/send_email_html.py
希望这些基本示例足以使您入门。
2条留言
我不想用电子邮件附加HTML文件。有什么方法可以发送具有HTML效果的HTML内容而无需附加文件,即在我们发送纯文本时是否直接附加文件。
提前致谢
维杰德
不确定可以。通过创建多部分电子邮件,读取该电子邮件的客户端应根据用户设置自动提取HTML部分。我猜唯一的选择是将HTML转储到纯文本电子邮件中。一世’我不确定该消息在另一端会如何显示,因为它将依赖电子邮件客户端为收件人设置其格式。