def send_email(fromAddr, passwd, toAddr, subject, body): server = SMTP('smtp.gmail.com',587) server.set_debuglevel(0) server.ehlo(fromAddr) server.starttls() server.ehlo(fromAddr) server.login(fromAddr,passwd) msg = MIMEText(body) msg['Subject'] = subject msg['From'] = fromAddr msg['To'] = toAddr server.sendmail(fromAddr,toAddr,msg.as_string() ) server.quit()
def mail(content): ret = True try: # msg = MIMEText('填写邮件内容', 'plain', 'utf-8') # msg = MIMEText(base64.b64encode(open('C:\Users\dell、\Downloads\\test.txt', 'rb').read()), 'plain', 'utf-8') # msg = MIMEText(base64.b64encode(open(content).read()), 'plain', 'utf-8') msg = MIMEText(open(content).read(), 'plain', 'utf-8') msg = M msg['From'] = formataddr(["FromRunoob", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To'] = formataddr(["FK", my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 msg['Subject'] = "菜鸟教程发送邮件测试" # 邮件的主题,也可以说是标题 server = smtplib.SMTP("smtp.163.com", 25) # 发件人邮箱中的SMTP服务器,端口是25 server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(my_sender, [ my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret = False print "失败" return ret
def _createBounceMessage(self, log, toAddress, msg): """ Create a multipart MIME message that will be sent to the user to indicate that their message has bounced. @param log: ??? @param toAddress: The email address that bounced @param msg: The message that bounced @return: L{MP.MIMEMultipart} """ bounceText = ( 'Your message to %(recipient)s, subject "%(subject)s", ' 'could not be delivered.') bounceText %= { 'recipient': toAddress, 'subject': msg.impl.getHeader(u'subject')} original = P.Parser().parse(msg.impl.source.open()) m = MMP.MIMEMultipart( 'mixed', None, [MT.MIMEText(bounceText, 'plain'), MT.MIMEText(log, 'plain'), MM.MIMEMessage(original)]) m['Subject'] = 'Unable to deliver message to ' + toAddress m['From'] = '<>' m['To'] = '' return m
def mail_message_to_mime_message(protocol_message): """Generate a MIMEMultitype message from protocol buffer. Generates a complete MIME multi-part email object from a MailMessage protocol buffer. The body fields are sent as individual alternatives if they are both present, otherwise, only one body part is sent. Multiple entry email fields such as 'To', 'Cc' and 'Bcc' are converted to a list of comma separated email addresses. Args: protocol_message: Message PB to convert to MIMEMultitype. Returns: MIMEMultitype representing the provided MailMessage. Raises: InvalidAttachmentTypeError when the file name of an attachment """ parts = [] if protocol_message.has_textbody(): parts.append(MIMEText.MIMEText(protocol_message.textbody())) if protocol_message.has_htmlbody(): parts.append(MIMEText.MIMEText(protocol_message.htmlbody(), _subtype='html')) if len(parts) == 1: payload = parts else: payload = [MIMEMultipart.MIMEMultipart('alternative', _subparts=parts)] result = MIMEMultipart.MIMEMultipart(_subparts=payload) for attachment in protocol_message.attachment_list(): file_name = attachment.filename() mime_type = _GetMimeType(file_name) maintype, subtype = mime_type.split('/') mime_attachment = MIMEBase.MIMEBase(maintype, subtype) mime_attachment.add_header('Content-Disposition', 'attachment', filename=attachment.filename()) mime_attachment.set_payload(attachment.data()) result.attach(mime_attachment) if protocol_message.to_size(): result['To'] = ', '.join(protocol_message.to_list()) if protocol_message.cc_size(): result['Cc'] = ', '.join(protocol_message.cc_list()) if protocol_message.bcc_size(): result['Bcc'] = ', '.join(protocol_message.bcc_list()) result['From'] = protocol_message.sender() result['Reply-To'] = protocol_message.replyto() result['Subject'] = protocol_message.subject() return result
def mail(sender, receiver, subject, message, final_message=True, server=None): """ :param sender: Then mail address of the sender, if has value `None` a default address will be generated using `get_default_email()` :type sender: str or None :param receiver: The mail address(es) of the reciever(s) :type receiver: str or [str] :param subject: Subject line :type subject: str :param message: Bulk of message :type message: str :param final_message (optional): If this is the final message intended to be sent by the server. If so, server will be disconnected afterwards. Default `True` :type final_message: bool :param server (optional): The server to send the message, if not supplied will create a default server using `get_server()` :type server: smtplib.SMTP :return: None """ if server is None: server = get_server() if server is None: return if not sender: sender = get_default_email() try: msg = MIMEMultipart() except TypeError: msg = MIMEMultipart.MIMEMultipart() msg['From'] = sender msg['To'] = receiver if isinstance(receiver, StringTypes) else ", ".join(receiver) msg['Subject'] = subject try: msg.attach(MIMEText(message)) except TypeError: msg.attach(MIMEText.MIMEText(message)) if isinstance(receiver, StringTypes): receiver = [receiver] try: server.sendmail(sender, receiver, msg.as_string()) except smtplib.SMTPException: _logger.error( "Could not mail, either no network connection or missing mailing functionality." ) if final_message: try: server.quit() except: pass
def sendmail(user, msg): #TODO: put these details in settings.py email_addr = get_user_email(user) msg = MIMEText(msg) msg['Subject'] = 'Pleiades Cluster Notification' msg['From'] = 'Pleiades Cluster<*****@*****.**>' msg['To'] = email_addr s = SMTP('student.up.ac.za', 25, 'Pleiades') s.sendmail('*****@*****.**', [email_addr], msg.as_string()) s.quit()
def alarm(self, *args, **kwargs): if not super(self.__class__, self).alarm(**kwargs): return False self._connect() for msg_to in self.self.opts["msg_to"]: msg = MIMEText(self.msg_tmpl.safe_substitute(kwargs)) msg['Subject'] = self.msg_tmpl_subj.safe_substitute(self.opts) msg['From'] = self.opts["msg_from"] msg['To'] = msg_to self.server.sendmail(self.opts["msg_from"], [msg_to], msg.as_string()) self._close() return True
def sendmail(content): msg = MIMEText(content,_subtype='html',_charset='utf-8') msg['Subject'] = '{time} 项目发布'.format(time=time.strftime('%Y-%m-%d %H:%M:%S')) msg['From'] = ("%s<"+options.mail_user+">") % (Header('发布任务','utf-8'),) msg['To'] = options.to_user msg["Accept-Charset"]="ISO-8859-1,utf-8" msg['Date'] = formatdate() server = smtplib.SMTP() try: server.connect(options.mail_server) server.login(options.mail_user,options.mail_password) server.sendmail(options.mail_user, options.to_user, msg.as_string()) app_log.error('send mail successfully') except Exception, e: app_log.info('send mail error: %s', e)
def mail(self, conntext): if (float(sys.getsizeof(conntext)) / 1024 / 1024) < 2: #2MB msg = MIMEText(conntext, _charset='utf-8') msg['Subject'] = self.subject msg['From'] = self.user msg['To'] = ",".join(self.to_list) try: server = smtplib.SMTP() server.connect(self.smtp, "25") # server.starttls() server.login(self.user, self.passwd) server.sendmail(self.user, self.to_list, msg.as_string()) server.quit() return self.status(True, '') except Exception, e: return self.status(False, e)
def send_rate_email(sender, receiver, cc_receiver, to, txt, title): # to = _format_addr(to) subject = title table = """ %s """ % (txt) msg = MIMEMultipart('related') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgText = MIMEText(table, 'html', 'utf-8') msgAlternative.attach(msgText) msg["Accept-Language"] = "zh-CN" msg["Accept-Charset"] = "ISO-8859-1,utf-8" if not isinstance(subject, unicode): subject = unicode(subject) msg['Subject'] = subject msg['To'] = ','.join(to) if cc_receiver != None: msg['CC'] = ','.join(cc_receiver) #----------------------------------------------------------- s = smtplib.SMTP('corp.chinacache.com') answer = s.sendmail(sender, receiver, msg.as_string()) s.close() logger.info( 'send_rate_email to: %s|| cc_receiver: %s|| receiver: %s|| answer: %s' % (to, cc_receiver, receiver, answer)) if str(answer) == '{}': return 'success' else: return 'fail'
def sendMail(from_addr, to_addr_dict, subject, mail_body, send_mail_server, ps, send_mail_port=587, send_file_name_as=None, send_file_path=None ): """ simple send mail with body and attachment :param from_addr: str|sender email address :param to_addr_dict: dict of list of str| list of receiver email address :param subject: str| subject of email :param mail_body: str|email body :param send_mail_server: str| :param ps: str| password :param send_mail_port: int| :param send_file_name_as: str|filename of the attachment :param send_file_path: str|path to the attachment """ logger.info("sending mail activity started") try: msg = MIMEMultipart.MIMEMultipart() msg['From'] = from_addr msg['To'] = ", ".join(to_addr_dict["To"]) msg['CC'] = ", ".join(to_addr_dict["CC"]) msg['BCC'] = ", ".join(to_addr_dict["BCC"]) msg['Subject'] = subject msg.attach(MIMEText.MIMEText(mail_body, 'plain')) #TODO : Attachment for mail ''' if send_file_name_as and send_file_path: attachment = open(send_file_path, "rb") part = MIMEBase.MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % send_file_name_as) msg.attach(part) ''' # Mailing server info server = smtplib.SMTP(send_mail_server, send_mail_port) server.starttls() server.login(from_addr, ps) text = msg.as_string() logger.info("sending email one by one") for k in to_addr_dict: if to_addr_dict[k]: logger.info('sending mail to %r', to_addr_dict[k]) server.sendmail(from_addr, to_addr_dict[k], text) server.quit() logger.info("Successfully sent email") except Exception, e: logger.exception('Error: unable to send email %r', e)
def _sendEmail(self, to, mess, subject): """Отправка на мыло с яндексовой почты""" msg = MM.MIMEMultipart() msg['From'] = Header(config.SMTP_DEFAULT_FROM, config.SMTP_ENCODING) msg['To'] = Header(to, config.SMTP_ENCODING) msg['Subject'] = Header(subject, config.SMTP_ENCODING) msg.attach(MT.MIMEText(mess, 'plain', config.SMTP_ENCODING)) text = msg.as_string() try: server = smtplib.SMTP(config.SMTP_SERVER, config.SMTP_PORT) server.ehlo() server.starttls() server.ehlo() server.login(config.SMTP_LOGIN, config.SMTP_PWD) res = server.sendmail(config.SMTP_DEFAULT_FROM, to, text) except smtplib.SMTPAuthenticationError as e: return False, e.smtp_error finally: if server is not None: server.quit() return res, text
def mime_add(msg, obj): from email import MIMEMultipart, MIMEText validate_message_structure(msg) # First, assure it to be multipart. if msg.is_multipart(): # This is already multipart. msg.attach(obj) return msg # If not, wrap the original Message with a new Multipart object. def move_headers(destmsg, srcmsg): # clear all headers for k in srcmsg.keys(): if k.lower() not in UNTOUCHED_HEADERS: del destmsg[k] # append headers (with avoiding duplication) for (k, v) in srcmsg.items(): if k.lower() not in UNTOUCHED_HEADERS: del srcmsg[k] destmsg[k] = v return # Create a Multipart message object. multi = MIMEMultipart.MIMEMultipart() # Move the old headers to the new one (EXCEPT mime-related headers). move_headers(multi, msg) multi.preamble = 'This message contains MIME objects.\n\n' # Sometime get_content_charset returns a unicode object! # We must coerce it to str. charset = msg.get_content_charset(config.MESSAGE_CHARSET) # Obtain the original content (which must be text) and reattach it. multi.attach(MIMEText.MIMEText(msg.get_payload(), _charset=str(charset))) # Attach the object. multi.attach(obj) return multi
def AddBody(self, message, text): # If a file has been specified as Body, then set Body to file contents. if os.path.isfile(text): body = FileOperations.open(text).read().strip() else: body = text message.attach(MIMEText.MIMEText(body, message))
def _send_new_password(self): player_login = self.line_edit_player_login.text() try: from_adress = "*****@*****.**" to_adress = ui_defs.players_infos(player_login)["email"] email_to_send = MIMEMultipart() email_to_send['From'] = from_adress email_to_send['To'] = to_adress email_to_send['Subject'] = 'New Time Bomb Password' new_password = ui_defs.generate_random_password() self._assign_password_to_player(player_login, new_password) email_body = ( 'Your new time bomb password : '******'ll could change it in your preferences.\n\nSee you soon in game!" ) email_to_send.attach(MIMEText(email_body, 'plain')) gmail_server = smtplib.SMTP('smtp.gmail.com', 587) gmail_server.starttls() gmail_server.login(from_adress, "TimeBomb78+") gmail_server.sendmail(from_adress, to_adress, str(email_to_send)) gmail_server.quit() ui_defs.message_box('OK', 'A new password has been send.') self.close() except KeyError: ui_defs.message_box('Wrong Login', 'This login doesn\'t exist.')
def send_email_notification(self, title, number): """ This function sends an email using Gmail SMTP Server to any email with a message telling that the manga has been sent to the kindle cloud. Keyword arguments: title - The title of the manga number - The chapter number of the manga """ msg = MIMEMultipart.MIMEMultipart() msg['from'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = 'Manga %s %s notification' % (title, number) msg.attach( MIMEText.MIMEText( 'The chapter number %s of manga %s has been sent to ' 'the kindle cloud' % (number, title))) smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "xxxpasswordxxx") smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) smtp.close()
def send_mail(sender, recipient, subject, body, file=None, filename=None): ''' Funktion zum versenden von Emails recipient muss als Liste übergeben werden body sollte einen formatierter String sein ''' msg = MIMEMultipart() msg["From"] = sender msg["To"] = COMMASPACE.join(recipient) # List to String msg["Subject"] = email.Header.Header(subject, 'UTF-8') msg.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8')) # Attachment von Dateien if file is not None: fn = file.split("/") fn = fn[-1] part = MIMEBase('application', 'octet-stream') part.set_payload(open(file, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=%s' % filename or fn) msg.attach(part) mailer = zope.component.getUtility(zope.sendmail.interfaces.IMailDelivery, name=u'uvcsite.maildelivery') mailer.send(sender, recipient, msg.as_string())
def build_and_send(self, recipient, subject, body, from_name=u'Mes souhaits', from_email=None): """Compose an email and send it.""" # pylint: disable-msg=E1101 msg = MIMEText.MIMEText(body.encode('utf-8')) if from_email is None: from_email = self.ADMIN else: msg['Sender'] = self.ADMIN # Ensure the recipient will be able to answer the mail msg['Reply-To'] = from_email fromaddr = Header.Header('%s <%s>' % (from_name, from_email), 'utf-8').encode() msg['From'] = fromaddr msg['User-Agent'] = 'Twisted Mail' msg['To'] = recipient msg['Subject'] = Header.Header(subject, 'utf-8') msg.set_charset('utf-8') self.sendmail(from_email, [recipient], msg.as_string())
def send_manga_throw_email(self, title, number): """ This function sends an email using Gmail SMTP Server to the kindle cloud with the comic attached into it. Keyword arguments: title - The title of the manga number - The chapter number of the manga """ msg = MIMEMultipart.MIMEMultipart() msg['from'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = '' msg.attach(MIMEText.MIMEText('')) part = MIMEBase.MIMEBase('application', "octet-stream") filename = title + "_" + str(number) + ".mobi" part.set_payload(open(filename, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(part) smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "xxxpasswordxxx") smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) smtp.close()
def MailLog(host, msg_from, msg_to, msg_subj): """Send stored log messages in an email This function constructs an email message with all log messages stored in the cStringIO buffer and sends the message to the specified recipient. To use this function, call SetLogBuffer() before generating the log messages. """ global _sio if _sio is None: return if host is None: host = 'localhost' contents = _sio.getvalue() msg = mime.MIMEText(contents) msg['Subject'] = msg_subj msg['From'] = msg_from msg['To'] = msg_to try: s = smtplib.SMTP() s.connect(host) s.sendmail(msg_from, [msg_to], msg.as_string()) s.close() except socket.error, mesg: SetLogConsole() logging.error('Socket error to ' + host + ' ' + str(mesg))
def email_results(msg_body): from_address = "*****@*****.**" recipients = ['*****@*****.**', '*****@*****.**'] to_address = ", ".join(recipients) msg = MIMEMultipart() msg['From'] = from_address msg['To'] = to_address msg['Subject'] = "FundBot" msg.attach(MIMEText(msg_body, 'plain')) for filename in os.listdir(os.path.join("plots")): if filename.endswith(".png"): attachment = open(os.path.join("plots", filename), "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('smtp.gmail.com', 587) server.starttls() server.login(from_address, "123456789") text = msg.as_string() server.sendmail(from_address, to_address, text) server.quit()
def main(): """Shows basic usage of the Google Admin-SDK Groups Migration API. Creates a Google Admin-SDK Groups Migration API service object and inserts a test email into a group. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('groupsmigration', 'v1', http=http) print('Warning: A test email will be inserted into the group entered.') groupId = raw_input( 'Enter the email address of a Google Group in your domain: ') # Format an RFC822 message message = MIMEText.MIMEText('This is a test.') # Generate a random 10 digit number for message Id. message['Message-ID'] = '<{0}-{1}>'.format(str(random.randrange(10**10)), groupId) message['Subject'] = 'Groups Migration API Test (Python)' message['From'] = '"Alice Smith" <*****@*****.**>' message['To'] = groupId message['Date'] = Utils.formatdate(localtime=True) stream = StringIO.StringIO() stream.write(message.as_string()) media = apiclient.http.MediaIoBaseUpload(stream, mimetype='message/rfc822') result = service.archive().insert(groupId=groupId, media_body=media).execute() print(result['responseCode'])
def AddBody(self, Message, Text): if os.path.isfile( Text ): # If a file has been specified as Body, then set Body to file contents Body = open(Text).read().strip() else: Body = Text Message.attach(MIMEText.MIMEText(Body, Message))
def create_message(sender, to, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An object containing a base64url encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send(self, sendto, subject, message): if isinstance(sendto, basestring): sendto = [sendto] for to in sendto: msg = MIMEText(message, "plain") msg["Subject"] = subject msg["To"] = to msg["From"] = self.sender if not self.debug: try: self.smtp.sendmail(self.sender, [to], msg.as_string()) except: pass else: print msg.as_string()
def sendMail(fromEmail, fromEmailName, toEmail, subject, body): msg = MIMEText.MIMEText(body) msg['Subject'] = subject msg['From'] = '"%s" <%s>' % (fromEmailName, fromEmail) msg['To'] = toEmail s = smtplib.SMTP() s.connect() s.sendmail(fromEmail, [toEmail], msg.as_string()) s.close()
def _sendEmail(self, subject, body): msg = MIMEText.MIMEText(body) msg['Subject'] = subject msg['From'] = self['from'] msg['To'] = self.uri s = smtplib.SMTP() s.connect() s.sendmail(self['from'], [self.uri], msg.as_string()) s.close()
def send_mail(error): #定义邮件的头部信息 header = Header.Header msg = MIMEText.MIMEText(error, 'plain', 'utf-8') msg['From'] = header(From) msg['To'] = header(To) msg['Subject'] = header(subject + '\n') #连接SMTP服务器,然后发送信息 smtp = SMTP(smtpserver) smtp.login(sender, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.close()
def send_w_html(subject, message, temail): txt = MIMEText(unicode(message), 'html', "utf-8") msg = MIMEMultipart("alternative") msg.attach(txt) femail = '*****@*****.**' msg['To'] = temail msg['From'] = femail msg['Subject'] = subject msg['Date'] = Utils.formatdate(localtime=1) print msg.as_string() s = smtplib.SMTP('mail.hector.com') s.sendmail(femail, temail.split(";"), msg.as_string()) s.close()
def send_w_att(subject, message, temail, attfileList): txt = MIMEText(unicode(message), 'plain', 'utf-8') msg = MIMEMultipart() msg.attach(txt) femail = '*****@*****.**' if attfileList is not None: for attfile in attfileList: file = open(attfile["path"], 'rb') att = MIMEText(file.read(), 'base64', 'utf8') file.close() att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="' + attfile[ "name"] + '"' msg.attach(att) msg['To'] = temail msg['From'] = femail msg['Subject'] = subject msg['Date'] = Utils.formatdate(localtime=1) print msg.as_string() s = smtplib.SMTP('mail.hector.com') s.sendmail(femail, temail.split(";"), msg.as_string()) s.close()
def send_mailText(self,sender,to_list,content,title): print 'nice' print title ,content mail_host="smtp.163.com" mail_user=sender[0] mail_pass =sender[2] # me="hello"+"<"+mail_user+"@"+mail_postfix+">" me = sender[1] msg = MIMEText(content,_subtype='plain',_charset='gb2312') msg['Subject'] = title msg['From'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False
def _generate_non_pgp_mime_email(self, signer, email, keyid, filename): '''Send the encrypted uid off to the user.''' msg = MIMEMultipart.MIMEMultipart() msg.epilogue = '' part = MIMEText.MIMEText(self._get_email_body(signer, keyid, email)) msg.attach(part) part = MIMEBase.MIMEBase('application', 'octet-stream') part.add_header('Content-Disposition', 'inline; filename="%s"' % os.path.basename(filename)) part.set_payload(open(filename, 'r').read()) msg.attach(part) return msg
def send_mail(mail_subject, mail_body, to_addr): from_addr = "*****@*****.**" server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_addr, email_password) msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = mail_subject msg.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'utf-8')) server.sendmail("*****@*****.**", to_addr, msg.as_string()) server.quit()
def send_mail(fromaddr, toaddr, subject, mail_body, send_mail_server, ps, send_mail_port=587, send_file_name_as=None, send_file_path=None): """ simple send mail with body and attachment :param fromaddr: str|sender email address :param toaddr: dict of list of str| list of receiver email address :param subject: str| subject of email :param mail_body: str|email body :param send_mail_server: str| :param ps: str| password :param send_mail_port: int| :param send_file_name_as: str|filename of the attachment :param send_file_path: str|path to the attachment """ msg = MIMEMultipart.MIMEMultipart() msg['From'] = fromaddr msg['To'] = ", ".join(toaddr["To"]) msg['CC'] = ", ".join(toaddr["CC"]) msg['BCC'] = ", ".join(toaddr["BCC"]) msg['Subject'] = subject msg.attach(MIMEText.MIMEText(mail_body, 'plain')) if send_file_name_as and send_file_path: attachment = open(send_file_path, "rb") part = MIMEBase.MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % send_file_name_as) msg.attach(part) server = smtplib.SMTP(send_mail_server, send_mail_port) server.starttls() server.login(fromaddr, ps) text = msg.as_string() for k in toaddr: if toaddr[k]: server.sendmail(fromaddr, toaddr[k], text) server.quit()
def send_email_through_gmail(subject, msg_body, to_addr='*****@*****.**'): server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login('*****@*****.**', '') msg = MIMEMultipart.MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = to_addr msg['Subject'] = subject msg.attach(MIMEText.MIMEText(msg_body, 'plain')) text = msg.as_string() server.sendmail('*****@*****.**', to_addr, text) server.close()
def createMessageWithAttachment( sender, to, subject, msgHtml, msgPlain, attachmentFile): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. msgHtml: Html message to be sent msgPlain: Alternative plain text message for older email clients attachmentFile: The path to the file to be attached. Returns: An object containing a base64url encoded email object. """ message = MIMEMultipart('mixed') message['to'] = to message['from'] = sender message['subject'] = subject messageA = MIMEMultipart('alternative') messageR = MIMEMultipart('related') messageR.attach(MIMEText(msgHtml, 'html')) messageA.attach(MIMEText(msgPlain, 'plain')) messageA.attach(messageR) message.attach(messageA) print("create_message_with_attachment: file: %s" % attachmentFile) content_type, encoding = mimetypes.guess_type(attachmentFile) fp = open(attachmentFile, 'rb') msg = email.MIMEBase.MIMEBase('text', "calendar", method="REQUEST", name=filename) msg.set_payload(fp.read()) fp.close()