def _fold(self, name, value, sanitize): parts = [] parts.append('%s: ' % name) if isinstance(value, str): if _has_surrogates(value): if sanitize: h = header.Header(value, charset=_charset.UNKNOWN8BIT, header_name=name) else: # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. parts.append(value) h = None else: h = header.Header(value, header_name=name) else: # Assume it is a Header-like object. h = value if h is not None: # The Header class interprets a value of None for maxlinelen as the # default value of 78, as recommended by RFC 2822. maxlinelen = 0 if self.max_line_length is not None: maxlinelen = self.max_line_length parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen)) parts.append(self.linesep) return ''.join(parts)
def cleanup_message(message, addr_headers=ADDR_HEADERS, param_headers=PARAM_HEADERS): """ Cleanup a `Message` handling header and payload charsets. Headers are handled in the most sane way possible. Address names are left in `ascii` if possible or encoded to `iso-8859-1` or `utf-8` and finally encoded according to RFC 2047 without encoding the address, something the `email` stdlib package doesn't do. Parameterized headers such as `filename` in the `Content-Disposition` header, have their values encoded properly while leaving the rest of the header to be handled without encoding. Finally, all other header are left in `ascii` if possible or encoded to `iso-8859-1` or `utf-8` as a whole. The message is modified in place and is also returned in such a state that it can be safely encoded to ascii. """ for key, value in message.items(): if key.lower() in addr_headers: addrs = [] for name, addr in utils.getaddresses([value]): best, encoded = best_charset(name) if PY_2: name = encoded name = header.Header( name, charset=best, header_name=key).encode() addrs.append(utils.formataddr((name, addr))) value = ', '.join(addrs) message.replace_header(key, value) if key.lower() in param_headers: for param_key, param_value in message.get_params(header=key): if param_value: best, encoded = best_charset(param_value) if PY_2: param_value = encoded if best == 'ascii': best = None message.set_param(param_key, param_value, header=key, charset=best) else: best, encoded = best_charset(value) if PY_2: value = encoded value = header.Header( value, charset=best, header_name=key).encode() message.replace_header(key, value) payload = message.get_payload() if payload and isinstance(payload, text_type): charset = message.get_content_charset() if not charset: charset, encoded = best_charset(payload) message.set_payload(payload, charset=charset) elif isinstance(payload, list): for part in payload: cleanup_message(part) return message
def run(self, context): LOG.info( "Sending email message " "[from=%s, to=%s, reply_to=%s, cc=%s, bcc=%s, subject=%s, " "using smtp=%s, body=%s...]", self.sender, self.to, self.reply_to, self.cc, self.bcc, self.subject, self.smtp_server, self.body[:128] ) if not self.html_body: message = text.MIMEText(self.body, _charset='utf-8') else: message = multipart.MIMEMultipart('alternative') message.attach(text.MIMEText(self.body, 'plain', _charset='utf-8')) message.attach(text.MIMEText(self.html_body, 'html', _charset='utf-8')) message['Subject'] = header.Header(self.subject, 'utf-8') message['From'] = self.sender message['Reply-To'] = header.Header(', '.join(self.reply_to)) message['To'] = ', '.join(self.to) if self.cc: message['cc'] = ', '.join(self.cc) rcpt = self.cc + self.bcc + self.to try: s = smtplib.SMTP(self.smtp_server) if self.password is not None: # Sequence to request TLS connection and log in (RFC-2487). s.ehlo() s.starttls() s.ehlo() s.login(self.sender, self.password) s.sendmail(from_addr=self.sender, to_addrs=rcpt, msg=message.as_string()) except (smtplib.SMTPException, IOError) as e: raise exc.ActionException("Failed to send an email message: %s" % e)
def run(self, context): LOG.info( "Sending email message " "[from=%s, to=%s, subject=%s, using smtp=%s, body=%s...]", self.sender, self.to, self.subject, self.smtp_server, self.body[:128]) message = text.MIMEText(self.body, _charset='utf-8') message['Subject'] = header.Header(self.subject, 'utf-8') message['From'] = self.sender message['To'] = ', '.join(self.to) try: s = smtplib.SMTP(self.smtp_server) if self.password is not None: # Sequence to request TLS connection and log in (RFC-2487). s.ehlo() s.starttls() s.ehlo() s.login(self.sender, self.password) s.sendmail(from_addr=self.sender, to_addrs=self.to, msg=message.as_string()) except (smtplib.SMTPException, IOError) as e: raise exc.ActionException("Failed to send an email message: %s" % e)
def stripSeq(input): subject = None while True: l = next(input) if l.startswith('Subject: '): # Subject appears subject = l continue elif subject and l[0] in ' \t': # Subject continues subject += l elif subject: # Subject ends s = subject[9:] s = decode_multiline_header(s) reformatted = reformat(s) if not reformatted: yield subject else: yield 'Subject: ' + header.Header(reformatted, 'utf-8').encode() + '\n' subject = None yield l elif l.strip() == '': yield l # mail body yield from input else: yield l
def _sanitize_header(self, name, value): if not isinstance(value, str): return value elif _has_surrogates(value): return header.Header(value, charset=(_charset.UNKNOWN8BIT), header_name=name) else: return value
def email_address_header(self): h = header.Header() h.append( '"%s"%s' % (self.get_pref('display_name'), ' ' if six.PY2 else '') ) # py2 needs explicit space for unicode/text_type cast of Header h.append('<%s>' % self.get_pref('email_address')) return h
def sender_mail(): smt_p = smtplib.SMTP() # 创建对象 smt_p.connect(host='smtp.qq.com', port=25) # 设置smtp服务器 sender = '*****@*****.**' password = "******" # 在qq邮箱设置开启SMTP服务并复制授权码到password smt_p.login(sender, password) # 进行邮箱登录一次,填写你本人的邮箱 receiver_addresses, count_num = [ '*****@*****.**', '*****@*****.**' ], 1 for email_address in receiver_addresses: # 表格中邮箱格式不正确,如有空字符,在发邮件的时候会出现异常报错,捕获到这些异常就跳过 try: msg = multipart.MIMEMultipart() msg['From'] = "zhenguo" # 设置发邮件人 msg['To'] = email_address # 收件人 # msg['Cc'] = '*****@*****.**' msg['subject'] = header.Header('通知', 'utf-8') # 主题名称 msg.attach( text.MIMEText( '您好!\n这是一封测试邮件,使用Python实现自动发邮件,请勿回复本邮件功能~\n\n 祝您工作愉快!', 'plain', 'utf-8')) xlsxpart = application.MIMEApplication( open(r'./data/email_test.xlsx', 'rb').read()) xlsxpart.add_header('Content-Disposition', 'attachment', filename='1.xlsx') msg.attach(xlsxpart) # 添加邮件的附件 smt_p.sendmail(sender, email_address, msg.as_string()) # 发送邮件 time.sleep(10) # sleep10秒避免发送频率过快,可能被判定垃圾邮件。 print('第%d次发送给%s' % (count_num, email_address)) count_num = count_num + 1 except Exception as e: print('第%d次给%s发送邮件异常' % (count_num, email_address)) continue smt_p.quit()
def SendEmail(user, psw, subject, AnnexList, toaddr, content, emailsrv): # print subject try: #创建一个带附件的实例 msg = multipart.MIMEMultipart() #构造附件 for Annex in AnnexList: annexfile = open(Annex, 'rb') annexdata = annexfile.read() annexfile.close() att = text.MIMEText(annexdata, 'base64', 'gb2312') att['Content-Type'] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % ( os.path.basename(Annex)) msg.attach(att) #构造正文 att = text.MIMEText(content, 'base64', 'gb2312') att['Content-Type'] = 'text/plain' att["Content-Transfer-Encoding"] = '7bit' msg.attach(att) #加邮件头 msg['to'] = toaddr msg['from'] = user msg['subject'] = header.Header(subject, 'gb2312') s = smtplib.SMTP(emailsrv) s.login(user, psw) s.sendmail(msg['from'], toaddr, msg.as_string()) s.quit() except: return False, "%s" % traceback.format_exc() return True, ""
def encode_header(s): tailed = s.rstrip(string.printable) topped = tailed.lstrip(string.printable) encoded = email_header.Header(topped, 'utf-8').encode() front = s[:len(tailed) - len(topped)] back_len = len(s) - len(tailed) back = "" if back_len == 0 else s[-back_len:] return front + encoded + back
def make_address_header(header_name, name, address): h = header.Header(charset=header_default_charset, header_name=header_name) if name: h.append(name) h.append("<%s>" % address, 'ascii') return h
def _encodeHeader(headerValue): """ Encodes a header value. Returns ASCII if possible, else returns an UTF-8 encoded e-mail header. """ try: return headerValue.encode('ascii', 'strict') except UnicodeError: encoded = headerValue.encode("utf-8") return header.Header(encoded, "UTF-8").encode()
def _sanitize_header(self, name, value): # If the header value contains surrogates, return a Header using # the unknown-8bit charset to encode the bytes as encoded words. if not isinstance(value, str): # Assume it is already a header object return value if _has_surrogates(value): return header.Header(value, charset=_charset.UNKNOWN8BIT, header_name=name) else: return value
def _fold(self, name, value, sanitize): parts = [] parts.append('%s: ' % name) if isinstance(value, str): if _has_surrogates(value): if sanitize: h = header.Header(value, charset=(_charset.UNKNOWN8BIT), header_name=name) else: parts.append(value) h = None else: h = header.Header(value, header_name=name) else: h = value if h is not None: maxlinelen = 0 if self.max_line_length is not None: maxlinelen = self.max_line_length parts.append(h.encode(linesep=(self.linesep), maxlinelen=maxlinelen)) parts.append(self.linesep) return ''.join(parts)
def generate_message(self, to, cc, bcc, subject, body): message = multipart.MIMEMultipart('alternative') message.attach(text.MIMEText(body, 'plain', _charset='utf-8')) message['From'] = CONF.reaper_notifier.sender message['To'] = ', '.join(to) if cc: message['Cc'] = ', '.join(cc) message['Subject'] = header.Header(subject, 'utf-8') return message
def Header(text, *more_text): '''Helper to make sure we encode headers properly''' if isinstance(text, header.Header): return text # email.header.Header handles str vs unicode differently # see http://docs.python.org/library/email.header.html#email.header.Header.append if type(text) != unicode: raise TypeError('This must be unicode: %r' % text) head = header.Header(text) for m in more_text: if type(m) != unicode: raise TypeError('This must be unicode: %r' % text) head.append(m) return head
def contact_view(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] message_text = form.cleaned_data['message'] subject = str(header.Header(name + " sent an email from " + email, "utf-8")) try: send_mail(subject, message_text, settings.DEFAULT_FROM_EMAIL, [email], fail_silently=False) except: return HttpResponse('Invalid Header Found') return redirect('success') else: return HttpResponse('Make sure all fields are valid') return render(request, "contact.html", {'form': form})
def sender_mail(): msg = multipart.MIMEMultipart() msg['From'] = 'Facker' msg['To'] = '**********@**.com' msg['subject'] = header.Header('subject', 'utf-8') texts = "You text!" msg.attach(text.MIMEText(texts, 'plain', 'utf-8')) try: smt_p = smtplib.SMTP() smt_p.connect(host='smtp.***.com', port=25) sender, password = '******', '****************' smt_p.login(sender, password) smt_p.sendmail(sender, '*****@*****.**', msg.as_string()) except Exception as e: print("发送失败!") smt_p.quit() print("发送成功!")
def sender_mail(): smt_p = smtplib.SMTP() smt_p.connect(host='smtp.qq.com', port=25) sender, password = '******', '**************' smt_p.login(sender, password) receiver_addresses = ['你准备发送的邮箱地址'] count_num = 1 for email_address in receiver_addresses: try: msg = multipart.MIMEMultipart() msg['From'] = 'Boss' msg['To'] = email_address msg['subject'] = header.Header('这个是标题', 'utf-8') msg.attach(text.MIMEText('这是内容', 'plain', 'utf-8')) smt_p.sendmail(sender, email_address, msg.as_string()) print('第%d次发送给%s' % (count_num, email_address)) time.sleep(10) count_num = count_num + 1 except Exception: print('第%d次发给%s异常' % (count_num, email_address)) smt_p.quit()
def sender_mail(): smt_p = smtplib.SMTP() smt_p.connect(host='smtp.qq.com', port=25) sender, password = '******', "atuiqvpuiwdiebdj" smt_p.login(sender, password) receiver_addresses, count_num = ['*****@*****.**'], 1 for email_address in receiver_addresses: try: msg = multipart.MIMEMultipart() msg['From'] = "zhenguo" # 发件人 msg['To'] = email_address #发件地址 msg['subject'] = header.Header('这是邮件主题通知', 'utf-8') #主题 msg.attach(text.MIMEText('这是一封测试邮件,请勿回复本邮件~', 'plain', 'utf-8')) #文本内容 smt_p.sendmail(sender, email_address, msg.as_string()) time.sleep(10) print('第%d次发送给%s' % (count_num, email_address)) count_num = count_num + 1 except Exception as e: print('第%d次给%s发送邮件异常' % (count_num, email_address)) continue smt_p.quit()
def sender_mail(): smt_p = smtplib.SMTP() smt_p.connect(host='smtp.qq.com', port=25) sender, password = '******', "rmedemkcefbkbhjc" smt_p.login(sender, password) receiver_addresses, count_num = [ '*****@*****.**', '*****@*****.**'], 1 for email_address in receiver_addresses: try: msg = multipart.MIMEMultipart() msg['From'] = "zhenguo" msg['To'] = email_address msg['subject'] = header.Header('这是邮件主题通知', 'utf-8') msg.attach(text.MIMEText( '这是一封测试邮件,请勿回复本邮件~', 'plain', 'utf-8')) smt_p.sendmail(sender, email_address, msg.as_string()) time.sleep(10) print('第%d次发送给%s' % (count_num, email_address)) count_num = count_num + 1 except Exception as e: print('第%d次给%s发送邮件异常' % (count_num, email_address)) continue smt_p.quit()
def build_message_root(newsletter, subscriber): msg = message.Message() msg['From'] = make_address_header('From', newsletter.author_name, newsletter.author_address) # Here we call .encode() because MailHost will assume that the headers are # strings, not header.Header instances. msg['To'] = make_address_header('To', subscriber.name, subscriber.email).encode() msg['Date'] = utils.formatdate() if newsletter.subject: msg['Subject'] = header.Header(newsletter.subject, charset=header_default_charset, header_name='Subject') if subscriber.removal_url: msg['List-Unsubscribe'] = '<%s>' % subscriber.removal_url msg['Mime-Version'] = '1.0' if (newsletter.reply_to_address and newsletter.reply_to_address != newsletter.author_address): msg['Reply-To'] = make_address_header('Reply-To', newsletter.reply_to_name, newsletter.reply_to_address) if (newsletter.sender_address and newsletter.sender_address != newsletter.author_address): msg['Sender'] = make_address_header('Sender', newsletter.sender_name, newsletter.sender_address) return msg
def send_mail(receivers, title, content, attachments=[], encoding='utf-8'): """ """ smtpServer = config.smtp_address smtpPort = config.smtp_port smtpUser = config.smtp_user smtpPassword = config.smtp_password smtpSender = config.smtp_user message = MIMEMultipart() contentPart = MIMEText(content, _subtype='html', _charset=encoding) message.attach(contentPart) # 创建附件部分 for filename in attachments[::-1]: # 获取不含路径的文件名 fn = path.split(filename)[-1] attMimeText = MIMEText(open(filename, 'rb').read(), 'base64', encoding) attMimeText["Content-Type"] = 'application/octet-stream' attMimeText[ "Content-Disposition"] = u'attachment; filename="%s"' % header.Header( fn).encode(encoding) message.attach(attMimeText) # Add Header message['to'] = ','.join(receivers) message['from'] = smtpSender message['subject'] = title # Send it smtp = smtplib.SMTP_SSL(smtpServer, smtpPort) smtp.login(smtpUser, smtpPassword) smtp.sendmail(smtpSender, receivers, message.as_string()) smtp.quit() # 返回成功 return True
def safe_header(value): """ prevent header injection attacks (the email library doesn't) """ if '\n' in value: return email_header.Header(value.encode('utf-8'), 'utf-8') else: return value
def email_address_header(self): h = header.Header() h.append('"%s" ' % self.get_pref('display_name')) h.append('<%s>' % self.get_pref('email_address')) return h
def smtpPostMail(SMTPserver: str = '', SMTPserverPort: int = '', username: str = '', password: str = '', senderName: str = '', senderAddr: str = '', reciverAddr: list = [str], subject: str = '', context: str = '', fileList: list = [str]): # 连接并登陆登录 # mailserver = smtplib.SMTP(SMTPserver, 25) # ssl的端口号默认是465 try: mailserver = smtplib.SMTP_SSL(host=SMTPserver, port=SMTPserverPort, timeout=15.0) except Exception as e: print('Sorry, Connect failed with the smtp server!!!') print('Here is the Exception msg:') print(e) exit(3) # 调试等级 # mailserver.set_debuglevel(1) mailserver.login(username, password) # 取出所有的接收者 recivers: str = u'' for reciver in reciverAddr: if reciver: recivers += u'%s <%s>' % (reciver, reciver) #拼接到一起 msg = MIMEMultipart() msg['From'] = _format_addr(u'%s <%s>' % (senderName, senderAddr)) msg['To'] = _format_addr(recivers) msg['Subject'] = Header.Header(u'%s' % subject, 'utf-8').encode() msg['Content-Type'] = "text/html; charset=utf-8" msg['Content-Transfer-Encoding'] = "quoted-printable" #文本段 msg.attach(MIMEText(context)) attachListDesc = '' #所有文件的文件列表(发送后,接收端无目录结构,建议添加参数,可选将目录压缩后发送) allFilesList: list = listAllFileFromPathSet(fileList) # 文件段(文件夹处理后生成的文件列表) for filePath in allFilesList: if os.path.exists(filePath) and os.path.isfile(filePath): file = open(filePath, 'rb') fileDataToEmail = MIMEApplication(file.read()) fileDataToEmail.add_header('Content-Disposition', 'attachment', filename=file.name) msg.attach(fileDataToEmail) attachListDesc += filePath attachListDesc += '\n\t' # print('已添加附件:%s' %(filePath)) print('\n\r #The mail to send seems like:') print(' ##From:' + u'%s <%s>' % (senderName, senderAddr)) print(' ##To:' + recivers) print(' ##Subject:' + subject) print(' ##Context:' + context) print(' ##AttachList:' + attachListDesc) try: # 开始发送(sender、reciver不可为中文!) mailserver.sendmail(from_addr=senderAddr, to_addrs=reciverAddr, msg=msg.as_string()) # mailserver.send_message(msg=msg, from_addr=senderAddr, to_addrs=reciverAddr) # mailserver.sendmail(from_addr='', to_addrs=reciver, msg=msg.__str__().encode("utf-8")) except smtplib.SMTPHeloError as e: print( 'Failed to get the hello msg from SMTP Server. Please check the SMTP settings for your mail account.' ) #接收方服务器拒绝收信 print('Here is the Exception msg:') print(e) exit(4) except smtplib.SMTPRecipientsRefused as e: print('This mail is refused by recipient\'s server.') #接收方服务器拒绝收信 print('Here is the Exception msg:') print(e) exit(4) except smtplib.SMTPSenderRefused as e: print( 'The post mail request was refused by SMTP Server. Please contract to server\'s administrator.' ) print('Here is the Exception msg:') print(e) exit(4) except smtplib.SMTPDataError as e: print('This server reply the error data. Please retry later') print('Here is the Exception msg:') print(e) exit(4) except smtplib.SMTPNotSupportedError as e: print('This server seems not support SMTP. Please check and retry.') print('Here is the Exception msg:') print(e) exit(4) except Exception as e: print( 'Sorry, something error! We failed to post this mail, you can retry later...' ) print('Here is the Exception msg:') exit(9) print('\n\r # Mail with subject:%s \n\rSended Sucessful !' % (subject)) #退出服务器 mailserver.quit() exit(0)
def _format_addr(s: str): name, addr = parseaddr(s) return formataddr( (Header.Header(name, 'utf-8').encode(), addr if isinstance(addr, str) else addr)) #仅仅Python3中生效,Python3默认的str就是unicode
def get_header_field(cls, message, name): field = message.get(name) h = header.Header(field) decode_h = header.decode_header(h) value, decode_type = decode_h[0] return value.decode(decode_type) if decode_type else value