Python Emailing with encoded deisgned ( html ) text - python

I have a working send email script which takes txt file and send it encoded.
i want to be able to design (html) this encoded txt in the email body.
i know how generally design a text in email body but i cant design the encoded txt in the html.
i want to combine the two scripts and be able to design the encoded text ( first script output) into the html design of the second script
first script send email ( Works but undesigned body ):
import smtplib
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# mailing cofig:
ID = 'XX
PASSWORD = XX
email_reciever = XX
filename = r".\Reports\Report.txt"
def send_email(subject, msg):
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(ID, PASSWORD)
message = 'Subject:{}\n\n{}'.format(subject, msg)
server.sendmail(ID, email_reciever, message)
# server.sendmail(ID, email_reciever, msg.as_string())
print('Succes')
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Your BeeHero Report'
msg['From'] = ID
msg['To'] = email_reciever
with open(filename, "r") as filename:
text = ''.join(filename.readlines()[1:])
msg.set_payload(text.encode())
subject = "BeeHero Report"
send_email(subject, msg)
output:
https://imgur.com/a/g6m0WKt
Second script ( designed body but not encoded as the first output)
# Sending email script Amit
import smtplib
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# mailing cofig:
ID = XX
PASSWORD = XX
email_reciever = XX
filename = r".\Reports\Report.txt"
def send_email(msg):
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(ID, PASSWORD)
server.sendmail(ID, email_reciever, msg.as_string())
print('Succes')
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Your BeeHero Report'
msg['From'] = ID
msg['To'] = email_reciever
with open(filename, "r") as filename:
text = ''.join(filename.readlines()[1:])
html = (f"""
<!DOCTYPE html>
<html>
<body>
<h1 style="color:SlateGray;">{text}</h1>
</body>
</html>
""")
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
send_email(msg)
output:
https://imgur.com/a/5wqUoSa

Related

python email multiple receiver, multiple attachment for error

def mail():
import os
import pandas as pd
import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email.mime.multipart import MIMEMultipart
from email import encoders
from PyQt5.QtCore import QDate, Qt
path = 'C:/Users/user/Desktop/pdf/'
contact = 'con1.xlsx'
df = pd.read_excel(str(path)+contact, endcoding ='utf8')
df.set_index('unyong', inplace = True)
now = QDate.currentDate()
filenm = [f for f in os.listdir(path) if f.endswith('.pdf')]
unyong_nm = []
for w in filenm:
a = w.find('_')
b = w.rfind('_')
unyong_nm.append(w[a+1:b])
unyong_nm = list(set(unyong_nm))
for i in range(0,len(unyong_nm)):
send_from = 'ss#ddd'
recipients = df.loc[unyong_nm[i],'email']
send_to = ",".join(recipients)
attach = [s for s in filenm if s.find(unyong_nm[i]) >-1 ]
username = 'sss#ssss'
password = 'sss'
subject = ('111'+now.toString('yyyy.MM')+'_'+unyong_nm[i]+str(i+1))
text = ('hi')
msg = MIMEMultipart()
msg['From'] = send_from
msg['To']= send_to
msg['Subject'] = subject
msg['Date']=formatdate(localtime=True)
filename_match = [s for s in filenm if s.find(unyong_nm[i]) >-1 ]
for file in filename_match:
part =MIMEBase('application','octet-stream')
part.set_payload(open(str(path)+file, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment', filename =file)
msg.attach(part)
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.sssss.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(username,password)
mailServer.sendmail(send_from, send_to, msg.as_string())
mailServer.close()
hi i have a problem with the email with attachment for statement.
the results of below def mail(),
multiple emails was sent to one person. (<- this is a error)
I want to send a each specific reciever with specific multiple attachments only once
why multiple email sented with diffrent number of attachements to one person.
the reciever have the 2 emails with a 1 attachment and, simultaneouly 2 attachment.
I want to send a email containg 2 attachments
please help me.
*CF) path containg thoes files:
['2221_sss_love.pdf', '2221_sss_happy.pdf', '2221_ddd_sad.pdf', '2221_ddd_lucky.pdf', 'con1.xlsx']
*result
unyong_nm = ['sss','ddd']
filenm = ['2221_sss_love.pdf', '2221_sss_happy.pdf', '2221_ddd_sad.pdf', '2221_ddd_lucky.pdf']
*CF) con1.xlsx file contenxt:
unyong email
sss 111#aaa
sss 777#bbb
ddd 666#sss
ddd 444#ccc
The code is sending an email for each attachment. By dedenting the mail-sending code, an email will be sent for each set of attachments grouped by 'ddd' or 'sss'.
for file in filename_match:
part = MIMEBase("application", "octet-stream")
part.set_payload(open(file, "rb").read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment", filename=file)
msg.attach(part)
msg.attach(MIMEText(text))
# Send mail outside the file grouping loop
mailServer = smtplib.SMTP("localhost", 1025)
mailServer.ehlo()
mailServer.sendmail(send_from, send_to, msg.as_string())
mailServer.close()
The recipient selection code
recipients = df.loc[unyong_nm[i],'email']
send_to = ",".join(recipients)
might need to be changed, I can't tell because the contents of the dataframe aren't provided in the question.

BCC not hidden on gmail using python smtplib

I am working on a python script to send email to my customer with a survey. I will send only one email with all my customers's emails in the BCC field so that I do not need to loop through all the emails. Everything works fine when I tested sending emails to my company's coleagues and also when I sent to my personal email, but whenever I send to a gmail account, the BCC field appears to not be hidden and show all the emails. I found this post Email Bcc recipients not hidden using Python smtplib and tried that solution as well, but as I am using a html body email, the emails were shown inside the body. Can anyone help me on this one?
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
def send_survey_mail():
template_path = 'template.html'
background_path = 'image.png'
button_path = 'image2.png'
try:
body = open(template_path, 'r')
msg = MIMEMultipart()
msg['Subject'] = 'Customer Survey'
msg['To'] = ', '.join(['myemail#domain.com.br', 'myemail2#domain.com'])
msg['From'] = 'mycompany#mycompany.com.br'
msg['Bcc'] = 'customer#domain.com'
text = MIMEText(body.read(), 'html')
msg.attach(text)
fp = open(background_path, 'rb')
img = MIMEImage(fp.read())
fp.close()
fp2 = open(button_path, 'rb')
img2 = MIMEImage(fp2.read())
fp2.close()
img.add_header('Content-ID', '<image1>')
msg.attach(img)
img2.add_header('Content-ID', '<image2>')
msg.attach(img2)
s = smtplib.SMTP('smtpserver')
s.sendmail('mycompany#mycompany.com.br',
['myemail#domain.com.br', 'myemail2#domain.com', 'customer#domain.com'],
msg.as_string())
s.quit()
except Exception as ex:
raise ex
send_survey_mail()
I removed the following line from the code and tried again. Now the email is not sent to my customer's Gmail email.
msg['Bcc'] = 'customer#gmail.com'
Just do not mention bcc mails in msg['To'] or msg['Cc']. Do it only in server.sendmail()
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from_addr = "your#mail.com"
to_addr = ["to#mail.com", "to2#mail.com"]
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = "SUBJECT"
body = "BODY"
msg.attach(MIMEText(body, 'plain'))
filename = "FILE.pdf"
attachment = open('/home/FILE.pdf', "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('.....', 587)
server.starttls()
server.login(from_addr, 'yourpass')
text = msg.as_string()
server.sendmail(from_addr, to_addr + [bcc#mail.com], text)
server.quit()
Did you try not to define the msg['BCC'] field? Setting this field forces it to be included. It is sufficient that the BCC email address is in the sendmail command's destination address list. Take a look at this question.
MAIL_FROM = default#server.com
MAIL_DL = default#server.com
def send(to, cc, bcc, subject, text, html):
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = MAIL_FROM
message["To"] = to
message["Cc"] = cc + "," + MAIL_DL
if html is not None:
body = MIMEText(html, "html")
else:
body = MIMEText(text)
message.attach(body)
server = smtplib.SMTP(MAIL_SERVER)
server.set_debuglevel(1)
server.sendmail(MAIL_DL, to.split(",") + bcc.split(","), message.as_string())
server.quit()
return {
"to": to,
"cc": cc,
"bcc": bcc,
"subject": subject,
"text": text,
"html": html,
}

send mail using python

Problem: when i send mail to user then from user name not seen in to user inbox only show email-id but i need user name of sender
from: demo#gmail.com username: Demo
To: demotest#gmail.com
CODE
import smtplib
fromaddr = From
toaddrs = To
msg = 'Why,Oh why!'
username = From
password = *******
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
smtplib does not include automatically any header, and you need to include a From: header, so you have to put one by yourself doing something like:
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
As you can se in the DOCS.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = 'demo#gmail.com'
toaddrs = 'demotest#gmail.com'
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = "good morning" #like name
msg['To'] = "GGGGGG"
body = MIMEText("example email body")
msg.attach(body)
username = 'demo#gmail.com'
password = ''
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
You just need to create the message correctly. I think the most convenient way to do it is using a special object for message. I placed a class which perhaps may help you to send messages in your project.
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
class EmailSender(object):
def __init__(self, subject, to, config):
self.__subject = subject
self.__to = tuple(to) if hasattr(to, '__iter__') else (to,)
self.__from = config['user']
self.__password = config['password']
self.__server = config['server']
self.__port = config['port']
self.__message = MIMEMultipart()
self.__message['Subject'] = self.__subject
self.__message['From'] = self.__from
self.__message['To'] = ', '.join(self.__to)
def add_text(self, text):
self.__message.attach(
MIMEText(text)
)
def add_image(self, img_path, name=None):
if name is None:
name = os.path.basename(img_path)
with open(img_path, 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name=name)
self.__message.attach(image)
def send(self):
server = smtplib.SMTP_SSL(self.__server, self.__port)
server.login(self.__from, self.__password)
server.sendmail(self.__from, self.__to, self.__message.as_string())
server.close()
sender = EmailSender("My letter", "my_target#email", {
'user': "from#email",
'password': "123456",
'server': "mail.google.com"
'port': 465
})
sender.add_text("Why,Oh why!")
sender.send()
Or go the easy way, by install yagmail and
Given:
To = 'someone#gmail.com'
From = 'me#gmail.com'
pwd = '******'
alias = 'someone'
Run:
import yagmail
yag = yagmail.SMTP(From, pwd)
yag.send({To: alias}, 'subject', 'Why,Oh why!')
Install might be done by pip install yagmail

Python SMTP/MIME Message body

I've been working on this for 2 days now and managed to get this script with a pcapng file attached to send but I cannot seem to make the message body appear in the email.
import smtplib
import base64
import ConfigParser
#from email.MIMEapplication import MIMEApplication
#from email.MIMEmultipart import MIMEMultipart
#from email.MIMEtext import MIMEText
#from email.utils import COMMASPACE, formatdate
Config = ConfigParser.ConfigParser()
Config.read('mailsend.ini')
filename = "test.pcapng"
fo = open(filename, "rb")
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent) # base 64
sender = 'notareal#email.com' # raw_input("Sender: ")
receiver = 'someother#fakeemail.com' # raw_input("Recipient: ")
marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")
body ="""
This is a test email to send an attachment.
"""
# Define the main headers
header = """ From: From Person <notareal#email.com>
To: To Person <someother#fakeemail.com>
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define message action
message_action = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body, marker)
# Define the attachment section
message_attachment = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" % (filename, filename, encoded_content, marker)
message = header + message_action + message_attachment
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email!"
except Exception:
print "Error: unable to send email"
My goal is to ultimately have this script send an email after reading the parameters from a config file and attach a pcapng file along with some other text data describing the wireshark event. The email is not showing the body of the message when sent. The pcapng file is just a test file full of fake ips and subnets for now. Where have I gone wrong with the message body?
def mail_man():
if ms == 'Y' or ms == 'y' and ms_maxattach <= int(smtp.esmtp_features['size']):
fromaddr = [ms_from]
toaddr = [ms_sendto]
cc = [ms_cc]
bcc = [ms_bcc]
msg = MIMEMultipart()
body = "\nYou're captured event is attached. \nThis is an automated email generated by Dumpcap.py"
msg.attach("From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % ms_subject
+ "X-Priority = %s\r\n" % ms_importance
+ "\r\n"
+ "%s\r\n" % body
+ "%s\r\n" % ms_pm)
toaddrs = [toaddr] + cc + bcc
msg.attach(MIMEText(body, 'plain'))
filename = "dcdflts.cong"
attachment = open(filename, "rb")
if ms_attach == 'y' or ms_attach == "Y":
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP(ms_smtp_server[ms_smtp_port])
server.starttls()
server.login(fromaddr, "YOURPASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddrs, text)
server.quit()
This is my second attempt, all "ms_..." variables are global through a larger program.
You shouldn't be reinventing the wheel. Use the mime modules Python has included in the standard library instead of trying to create the headers on your own. I haven't been able to test it out but check if this works:
import smtplib
import base64
import ConfigParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
filename = "test.pcapng"
with open(filename, 'rb') as fo:
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent)
sender = 'notareal#email.com' # raw_input("Sender: ")
receiver = 'someother#fakeemail.com' # raw_input("Recipient: ")
marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")
body ="""
This is a test email to send an attachment.
"""
message = MIMEMultipart(
From=sender,
To=receiver,
Subject='Sending Attachment')
message.attach(MIMEText(body)) # body of the email
message.attach(MIMEApplication(
encoded_content,
Content_Disposition='attachment; filename="{0}"'.format(filename)) # b64 encoded file
)
try:
smtpObj = smtplib.SMTP('smtp.gmail.com')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email!"
except Exception:
print "Error: unable to send email"
I've left off a few parts (like the ConfigParser variables) and demonstrated only the email related portions.
References:
How to send email attachments with Python
Figured it out, with added ConfigParser. This is fully functional with a .ini file
import smtplib
####import sys#### duplicate
from email.parser import Parser
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import ConfigParser
def mail_man(cfg_file, event_file):
# Parse email configs from cfg file
Config = ConfigParser.ConfigParser()
Config.read(str(cfg_file))
mail_man_start = Config.get('DC_MS', 'ms')
security = Config.get('DC_MS', 'ms_security')
add_attachment = Config.get('DC_MS', 'ms_attach')
try:
if mail_man_start == "y" or mail_man_start == "Y":
fromaddr = Config.get("DC_MS", "ms_from")
addresses = [Config.get("DC_MS", "ms_sendto")] + [Config.get("DC_MS", "ms_cc")] + [Config.get("DC_MS", "ms_bcc")]
msg = MIMEMultipart() # creates multipart email
msg['Subject'] = Config.get('DC_MS', 'ms_subject') # sets up the header
msg['From'] = Config.get('DC_MS', 'ms_from')
msg['To'] = Config.get('DC_MS', 'ms_sendto')
msg['reply-to'] = Config.get('DC_MS', 'ms_replyto')
msg['X-Priority'] = Config.get('DC_MS', 'ms_importance')
msg['CC'] = Config.get('DC_MS', 'ms_cc')
msg['BCC'] = Config.get('DC_MS', 'ms_bcc')
msg['Return-Receipt-To'] = Config.get('DC_MS', 'ms_rrr')
msg.preamble = 'Event Notification'
message = '... use this to add a body to the email detailing event. dumpcap.py location??'
msg.attach(MIMEText(message)) # attaches body to email
# Adds attachment if ms_attach = Y/y
if add_attachment == "y" or add_attachment == "Y":
attachment = open(event_file, "rb")
# Encodes the attachment and adds it to the email
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename = %s" % event_file)
msg.attach(part)
else:
print "No attachment sent."
server = smtplib.SMTP(Config.get('DC_MS', 'ms_smtp_server'), Config.get('DC_MS', 'ms_smtp_port'))
server.ehlo()
server.starttls()
if security == "y" or security == "Y":
server.login(Config.get('DC_MS', 'ms_user'), Config.get('DC_MS', 'ms_password'))
text = msg.as_string()
max_size = Config.get('DC_MS', 'ms_maxattach')
msg_size = sys.getsizeof(msg)
if msg_size <= max_size:
server.sendmail(fromaddr, addresses, text)
else:
print "Your message exceeds maximum attachment size.\n Please Try again"
server.quit()
attachment.close()
else:
print "Mail_man not activated"
except:
print "Error! Something went wrong with Mail Man. Please try again."

How do I send attachments using SMTP?

I want to write a program that sends email using Python's smtplib. I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in on how attachments work in SMTP?
Here is an example of a message with a PDF attachment, a text "body" and sending via Gmail.
# Import smtplib for the actual sending function
import smtplib
# For guessing MIME type
import mimetypes
# Import the email modules we'll need
import email
import email.mime.application
# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'Greetings'
msg['From'] = 'xyz#gmail.com'
msg['To'] = 'abc#gmail.com'
# The main body is just another attachment
body = email.mime.Text.MIMEText("""Hello, how are you? I am fine.
This is a rather nice letter, don't you think?""")
msg.attach(body)
# PDF attachment
filename='simple-table.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)
# send via Gmail server
# NOTE: my ISP, Centurylink, seems to be automatically rewriting
# port 25 packets to be port 587 and it is trashing port 587 packets.
# So, I use the default port 25, but I authenticate.
s = smtplib.SMTP('smtp.gmail.com')
s.starttls()
s.login('xyz#gmail.com','xyzpassword')
s.sendmail('xyz#gmail.com',['xyz#gmail.com'], msg.as_string())
s.quit()
Here's an example I snipped out of a work application we did. It creates an HTML email with an Excel attachment.
import smtplib,email,email.encoders,email.mime.text,email.mime.base
smtpserver = 'localhost'
to = ['email#somewhere.com']
fromAddr = 'automated#hi.com'
subject = "my subject"
# create html email
html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
html +='<body style="font-size:12px;font-family:Verdana"><p>...</p>'
html += "</body></html>"
emailMsg = email.MIMEMultipart.MIMEMultipart('alternative')
emailMsg['Subject'] = subject
emailMsg['From'] = fromAddr
emailMsg['To'] = ', '.join(to)
emailMsg['Cc'] = ", ".join(cc)
emailMsg.attach(email.mime.text.MIMEText(html,'html'))
# now attach the file
fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
fileMsg.set_payload(file('exelFile.xls').read())
email.encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=anExcelFile.xls')
emailMsg.attach(fileMsg)
# send email
server = smtplib.SMTP(smtpserver)
server.sendmail(fromAddr,to,emailMsg.as_string())
server.quit()
What you want to check out is the email module. It lets you build MIME-compliant messages that you then send with smtplib.
Well, attachments are not treated in any special ways, they are "just" leaves of the Message-object tree. You can find the answers to any questions regarding MIME-compliant mesasges in this section of the documentation on the email python package.
In general, any kind of attachment (read: raw binary data) can be represented by using base64
(or similar) Content-Transfer-Encoding.
Here's how to send e-mails with zip file attachments and utf-8 encoded subject+body.
It was not straightforward to figure this one out, due to lack of documentation and samples for this particular case.
Non-ascii characters in replyto needs to be encoded with, for instance, ISO-8859-1. There probably exists a function that can do this.
Tip:Send yourself an e-mail, save it and examine the content to figure out how to do the same thing in Python.
Here's the code, for Python 3:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:set ts=4 sw=4 et:
from os.path import basename
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import parseaddr, formataddr
from base64 import encodebytes
def send_email(recipients=["somebody#somewhere.xyz"],
subject="Test subject æøå",
body="Test body æøå",
zipfiles=[],
server="smtp.somewhere.xyz",
username="bob",
password="password123",
sender="Bob <bob#somewhere.xyz>",
replyto="=?ISO-8859-1?Q?M=F8=F8=F8?= <bob#somewhere.xyz>"): #: bool
"""Sends an e-mail"""
to = ",".join(recipients)
charset = "utf-8"
# Testing if body can be encoded with the charset
try:
body.encode(charset)
except UnicodeEncodeError:
print("Could not encode " + body + " as " + charset + ".")
return False
# Split real name (which is optional) and email address parts
sender_name, sender_addr = parseaddr(sender)
replyto_name, replyto_addr = parseaddr(replyto)
sender_name = str(Header(sender_name, charset))
replyto_name = str(Header(replyto_name, charset))
# Create the message ('plain' stands for Content-Type: text/plain)
try:
msgtext = MIMEText(body.encode(charset), 'plain', charset)
except TypeError:
print("MIMEText fail")
return False
msg = MIMEMultipart()
msg['From'] = formataddr((sender_name, sender_addr))
msg['To'] = to #formataddr((recipient_name, recipient_addr))
msg['Reply-to'] = formataddr((replyto_name, replyto_addr))
msg['Subject'] = Header(subject, charset)
msg.attach(msgtext)
for zipfile in zipfiles:
part = MIMEBase('application', "zip")
b = open(zipfile, "rb").read()
# Convert from bytes to a base64-encoded ascii string
bs = encodebytes(b).decode()
# Add the ascii-string to the payload
part.set_payload(bs)
# Tell the e-mail client that we're using base 64
part.add_header('Content-Transfer-Encoding', 'base64')
part.add_header('Content-Disposition', 'attachment; filename="%s"' %
os.path.basename(zipfile))
msg.attach(part)
s = SMTP()
try:
s.connect(server)
except:
print("Could not connect to smtp server: " + server)
return False
if username:
s.login(username, password)
print("Sending the e-mail")
s.sendmail(sender, recipients, msg.as_string())
s.quit()
return True
def main():
send_email()
if __name__ == "__main__":
main()
# -*- coding: utf-8 -*-
"""
Mail sender
"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import pystache
import codecs
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
HOST = 'smtp.exmail.qq.com'
PORT = 587
USER = 'your#mail.com'
PASS = 'yourpass'
FROM = 'your#mail.com'
SUBJECT = 'subject'
HTML_NAME = 'tpl.html'
CSV_NAME = 'list.txt'
FAILED_LIST = []
def send(mail_receiver, mail_to):
# text = mail_text
html = render(mail_receiver)
# msg = MIMEMultipart('alternative')
msg = MIMEMultipart('mixed')
msg['From'] = FROM
msg['To'] = mail_to.encode()
msg['Subject'] = SUBJECT.encode()
# msg.attach(MIMEText(text, 'plain', 'utf-8'))
msg.attach(MIMEText(html, 'html', 'utf-8'))
try:
_sender = smtplib.SMTP(
HOST,
PORT
)
_sender.starttls()
_sender.login(USER, PASS)
_sender.sendmail(FROM, mail_to, msg.as_string())
_sender.quit()
print "Success"
except smtplib.SMTPException, e:
print e
FAILED_LIST.append(mail_receiver + ',' + mail_to)
def render(name):
_tpl = codecs.open(
'./html/' + HTML_NAME,
'r',
'utf-8'
)
_html_string = _tpl.read()
return pystache.render(_html_string, {
'receiver': name
})
def main():
ls = open('./csv/' + CSV_NAME, 'r')
mail_list = ls.read().split('\r')
for _receiver in mail_list:
_tmp = _receiver.split(',')
print 'Mail: ' + _tmp[0] + ',' + _tmp[1]
time.sleep(20)
send(_tmp[0], _tmp[1])
print FAILED_LIST
main()

Categories