Python – mail / email senden

6. Juni 2013 at 21:45
Print Friendly, PDF & Email

Hauptprogramm

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# send email via smtp
# 2013-06-06 V0.1 by Thomas Hoeser
# 
 
from avrio_mail import *
 
send_mail("Fire Alarm","Your house is burning down.")

 

Das Modul “avrio_mail.py” dazu:

 

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# send email via smtp
# 2013-06-06 V0.1 by Thomas Hoeser
# 
import sys
import smtplib
 
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
 
mail_server   = 'smtp.web.de'		# Mail Server
mail_account  = 'xxx.yyy@web.de'	# name of mail account
mail_password = 'zzzz'			# password
addr_sender   = 'bill.gates@microsoft.de'	# sender email
addr_receiver = 'bill.gates@microsoft.de'	# receiver email
 
# --------------------------------------------------------------------------------
def send_mail(title,message):
 
	# Create message container - the correct MIME type is multipart/alternative.
	msg = MIMEMultipart('alternative')
	msg['Subject'] = title
	msg['From'] = addr_sender
	msg['To'] = addr_receiver
 
	# Create the body of the message (a plain-text and an HTML version).
	text = message
 
	html = """\
<html>
  <head></head>
  <body>
    <h>
"""
 
	html += message
	html += """\
</h>
	<p> This is a service provided by raspberry</p>
  </body>
</html>
"""
	# print 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.
	msg.attach(part1)
	msg.attach(part2)
 
	try:
		# Send the message via local SMTP server.
		mailsrv = smtplib.SMTP(mail_server)
		mailsrv.login(mail_account,mail_password)
		# sendmail function takes 3 arguments: sender's address, recipient's address and message to send - here it is sent as one string.
		mailsrv.sendmail(addr_receiver, addr_receiver, msg.as_string())
		mailsrv.quit()
		print "Successfully sent email"
	except:
		print "Error: unable to send email"

 

Die Sender- und Empfänger-adressen zeigen etwas eigenartiges:

–          Die Mail-Adressen müssen ein gültiges Format ausweisen: name@domain.de

–          Weder Sender- noch Empfänger-Adresse muss existieren

–          ABER …. Wenn ein Adresse verwendet, die auf dem verwendeten Mail-Server liegt, MUSS die existieren
Es geht:               Mail-Server = smtp.hoeser-medien.de & Empfänger/Sender diegibtesnicht@gmx.de  | denauchnicht@gmx.de
Geht nicht          Mail-Server = smtp.gmx.de                       & Empfänger/Sender diegibtesnicht@gmx.de  | denauchnicht@gmx.de

 

Tags: