summaryrefslogtreecommitdiffstats
path: root/invoice/mailhelper.py
blob: 0da8cd8069f2549db676a06685295c79c1b03ec1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.header import Header

import time, email.utils, smtplib

class MAIL(object):
	def __init__(self, server, port, username, password):
		self.__server = server
		self.__port = port
		self.__username = username
		self.__password = password
		pass

	def generate_mail(self, receiver, subject, message, attachments = None, timestamp=time.time(), cc = None):
		msg = MIMEMultipart()
		msg["From"] = "KtT-Shopsystem <shop@kreativitaet-trifft-technik.de>"
		msg["Date"] = email.utils.formatdate(timestamp, True)

		try:
			if receiver[0].encode("ascii"):
				msg["To"] = receiver[0] + " <" + receiver[1] + ">"
		except UnicodeError:
			msg["To"] = Header(receiver[0], 'utf-8') + " <" + receiver[1] + ">"

		if cc != None:
			msg["Cc"] = cc
		msg["Subject"] = Header(subject, 'utf-8')
		msg.preamble = "Please use a MIME aware email client!"

		msg.attach(MIMEText(message, 'plain', 'utf-8'))

		if isinstance(attachments, dict):
			for name, data in attachments.items():
				if name.endswith("pdf"):
					pdf = MIMEApplication(data, 'pdf')
					pdf.add_header('Content-Disposition', 'attachment', filename = name)
					msg.attach(pdf)
				if name.endswith("db"):
					file = MIMEApplication(data)
					file.add_header('Content-Disposition', 'attachment', filename = name)
					msg.attach(file)
				else:
					txt = MIMEText(data, 'plain', 'utf-8')
					txt.add_header('Content-Disposition', 'attachment', filename = name)
					msg.attach(txt)
		elif attachments is not None:
			pdf = MIMEApplication(attachments, 'pdf')
			pdf.add_header('Content-Disposition', 'attachment', filename = 'rechnung.pdf')
			msg.attach(pdf)

		return msg

	def send_mail(self, mail, receiver):
		server = smtplib.SMTP(self.__server, self.__port)
		server.starttls()
		if self.__username != "":
			server.login(self.__username, self.__password)
		maildata = mail.as_string()
		server.sendmail(mail["From"], receiver, maildata)
		server.quit()