def sendemail(from_addr, to_addr_list, cc_addr_list, subject, message, files, smtpserver='smtp.gmail.com:587'): msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = from_addr msg['To'] = to_addr_list msg['Cc'] = cc_addr_list text = message msg.attach(MIMEText(text)) #Mail with attachment ctype = "application/octet-stream" maintype, subtype = ctype.split('/', 1) if maintype == 'image': fp = open(files, 'rb') part = MIMEImage(fp.read()) fp.close() encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=files) msg.attach(part) elif maintype == 'audio': fp = open(files, 'rb') part = MIMEAudio(fp.read()) fp.close() encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=files) msg.attach(part) else: fp = open(files, 'rb') part = MIMEApplication(maintype, subtype) part.set_payload(fp.read()) fp.close() encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=files) msg.attach(part) #Login Credentials username = from_addr password = getpass('Enter Password:'******'Email Address not Valid'
def sendMail(to, subject, text, files=[], server="smtp.gmail.com"): assert type(to) == list assert type(files) == list fro = "*****@*****.**" msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for file in files: if '.png' in file: part = MIMEImage(file, _subtype="png") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment;filename="%s"' % os.path.basename(file)) else: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment;filename="%s"' % os.path.basename(file)) msg.attach(part) if 'cnrs-orleans' in server: smtp = smtplib.SMTP(server, 25) if 'smtp.gmail.com' in server: print("smtplib.SMTP") smtp = smtplib.SMTP(server, 587) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login("undysputed.mailbox", "nenufarpulsar") #smtp.set_debuglevel(1) print("smtp.sendmail") smtp.sendmail(fro, to, msg.as_string()) print("smtp.close") smtp.close()
def build(self, meAddress, ToAddressList, subject, message, AttachPathList): dateStr = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.localtime()) self.__MeAddress = meAddress self.__ToAddressList = ToAddressList self.__Subject = subject self.__Message = message self.__oMIME = MIMEMultipart() self.__oMIME['Date'] = dateStr messageIdStr = '<' + str(int(time.time())) + '-' + str(random.randint(0,9999999)) + '@buscaplus.com' + '>' self.__oMIME['Message-ID'] = messageIdStr self.__oMIME['Subject'] = subject self.__oMIME['From'] = meAddress self.__oMIME['To'] = string.join(ToAddressList, ',') # Add Text oPart = MIMEText(message, 'plain', self.__CharSet) self.__oMIME.attach(oPart) # Add Attachments i = 0 while i != len(AttachPathList): attachPath = AttachPathList[i] PathList = attachPath.split('/') fileName = PathList[len(PathList)-1] attachType, attachEncoding = mimetypes.guess_type(attachPath) mainType, subType = attachType.split('/') if mainType == 'image': fp = open(attachPath, 'rb') msg = MIMEImage(fp.read(), _subtype=subType) fp.close() elif mainType == 'audio': fp = open(attachPath, 'rb') msg = MIMEAudio(fp.read(), _subtype=subType) fp.close() else: fp = open(attachPath, 'rb') msg = MIMEBase(mainType, subType) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=fileName) self.__oMIME.attach(msg) i = i + 1
def get_binpart(d={}, ctype=''): #print d if d.get('raw'): if ctype == 'image': att = MIMEImage(d['raw']) else: att = MIMEApplication(d['raw']) #del att['Content-Type'] # check if headers are defined for kh in d.keys(): if re.match('^h_(.*)$', kh): #print kh hn = re.match('^h_(.*)$', kh) #att[h.group(1)] = d[kh] # if headers were defined and has some value and # this same header is defined as a default header with MIME # object than remove the default header before adding your own if att[hn.group(1)] and d[kh] != '': #print 'exist=',att[hn.group(1)] #del att[hn.group(1)] att.replace_header(hn.group(1), d[kh]) elif d[kh] != '': att.add_header(hn.group(1), d[kh]) if d.get('b64'): att = MIMEBase('application', 'octet-stream') for kh in d.keys(): if re.match('^h_(.*)$', kh): #print kh hn = re.match('^h_(.*)$', kh) if att[hn.group(1)] and d[kh] != '': att.replace_header(hn.group(1), d[kh]) elif d[kh] != '': #print 'ddd=',d[kh] att.add_header(hn.group(1), d[kh]) att.set_payload("\n".join(d['b64'])) #print d['b64'] #print att return att
def add_image(self, image_file): """ image_file: 待添加的图片,会展示在邮件正文中 """ basename = os.path.basename(image_file) image = MIMEImage('image', basename.split('.')[-1], filename=basename) cid = self._image_count image.add_header('Content-Disposition', 'attachment', filename=basename) image.add_header("Content-ID", "<{cid}>".format(cid=cid)) image.add_header('X-Attachment-Id', '{cid}'.format(cid=cid)) with open(image_file) as f: image.set_payload(f.read()) encoders.encode_base64(image) self._msg.attach(image) self.add_html('<strong>{filename}</strong><center><img src="cid:{cid}"></center>' .format(filename=basename, cid=cid)) self._image_count += 1 logger.info('add image:%s, image count:%s' % (basename, self._image_count))
def sendMail(self, rcpt, subject, text): send_from = "%s@%s" % (self.avatarId.username, self.avatarId.dom) send_to = [] rcpt.replace(';', ',') for r in rcpt.split(','): n = r.strip() if '@' in n: send_to.append(n) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject # Figure out our multi-part id's idmapper = {} isinline = [] cnt = 0 for filename, real in self.attachments.items(): cnt += 1 # RFC 2111 wins the retard prize! id = "%s@%s" % (sha.sha(str(cnt) + real[0]).hexdigest(), self.avatarId.dom) idmapper[filename] = id mpath = '/mail/mdata/%s/%s' % (self.avatarId.username, real[0]) if mpath in text: isinline.append(filename) text = text.replace(mpath, 'cid:%s' % id) msg.attach( MIMEText( """<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head></head><body> %s </body></html>""" % text, 'html')) for filename, real in self.attachments.items(): f = self.static + self.avatarId.username + '/' + real[0] if filename in isinline: part = MIMEImage(open(f, "rb").read()) else: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) email.Encoders.encode_base64(part) part.add_header('Content-ID', '<%s>' % idmapper[filename]) if filename in isinline: part.add_header('Content-Disposition', 'inline; filename="%s"' % filename) else: part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) msg.attach(part) from twisted.mail import smtp def finished(_): print "Mail sent", _ return True # Clean realFrom if "<" in send_from: realFrom = send_from.split('<')[-1].split('>')[0] else: realFrom = send_from return smtp.sendmail('127.0.0.1', realFrom, [send_to], msg.as_string()).addBoth(finished)