示例#1
0
 def _getProposalInput(self):
     prop = self.proposalNum.text()
     title = self.expTitle.text()
     username = self.userName.text()
     remark = self.remark.text()
     proposaldir = self.proposalDir.text()
     if proposaldir and not os.path.isdir(proposaldir):
         QMessageBox.critical(
             self, 'Error', 'The provided proposal path '
             'does not exist!')
         raise ConfigurationError('')
     if not os.access(proposaldir, os.W_OK):
         QMessageBox.critical(
             self, 'Error', 'Don\'t have permission to '
             'write in the proposal path! Please choose '
             'a different one!')
         raise ConfigurationError('')
     try:
         useremail = mailaddress(self.userEmail.text())
     except ValueError:
         QMessageBox.critical(
             self, 'Error', 'The user email entry is '
             'not  a valid email address')
         raise ConfigurationError('') from None
     return prop, title, username, useremail, proposaldir, remark
示例#2
0
def splitUsers(users_str):
    """Split string from the combineUsers() format."""
    users = []
    for userstr in users_str.split(';'):
        user = {}
        userstr = userstr.strip()
        if '(' in userstr and userstr.endswith(')'):
            userstr, _, affiliation = userstr[:-1].partition('(')
            user['affiliation'] = affiliation.strip()
            userstr = userstr.strip()
        if '<' in userstr and userstr.endswith('>'):
            userstr, _, email = userstr[:-1].partition('<')
            user['email'] = mailaddress(email)
        user['name'] = userstr.strip()
        users.append(user)
    return users
示例#3
0
 def _getProposalInput(self):
     prop = self.proposalNum.text()
     title = self.expTitle.text().encode('utf-8')
     users = self.users.text().encode('utf-8')
     try:
         local = mailaddress(self.localContact.text().encode('utf-8'))
     except ValueError:
         QMessageBox.critical(
             self, 'Error', 'The local contact entry is '
             'not  a valid email address')
         raise ConfigurationError('')
     emails = self.notifEmails.toPlainText().encode('utf-8').strip()
     emails = emails.split(b'\n') if emails else []
     if local and local not in emails:
         emails.append(local)
     dataEmails = self.dataEmails.toPlainText().encode('utf-8').strip()
     dataEmails = dataEmails.split(b'\n') if dataEmails else []
     errorbehavior = 'abort' if self.errorAbortBox.isChecked() else 'report'
     return prop, title, users, local, emails, dataEmails, errorbehavior
示例#4
0
def sendMail(mailserver,
             receiverlist,
             mailsender,
             topic,
             body,
             attach_files=(),
             debuglevel=0):
    """Sends an email to a list of receivers with given topic and content via
    the given server.

    Returns True if successful and list of error-messages else

    mailserver is a working E-Mailserver accepting mail from us,
    receiverlist is a not empty list of valid E-Mail adresses or a string with
    comma-separated E-Mail adresses
    sender is a valid E-Mail-address,
    topic and body are strings and the list of attach_files may be empty
    if attach_files is not empty, it must contain names of existing files!
    """
    # try to check parameters
    errors = []
    if isinstance(receiverlist, string_types):
        receiverlist = receiverlist.replace(',', ' ').split()
    try:
        mailaddress(mailsender)
    except ValueError as e:
        errors.append('Mailsender: %s' % e)
    for a in receiverlist:
        try:
            mailaddress(a)
        except ValueError as e:
            errors.append('Receiver: %s' % e)
    for fn in attach_files:
        if not path.exists(fn):
            errors.append(
                'Attachment %r does not exist, please check config!' % fn)
        elif not path.isfile(fn):
            errors.append('Attachment %r is not a file, please check config!' %
                          fn)
    if errors:
        return ['No mail sent because of invalid parameters'] + errors

    # construct msg according to
    # http://docs.python.org/library/email-examples.html#email-examples
    receivers = ', '.join(receiverlist)
    msg = MIMEMultipart()
    msg['Subject'] = topic
    msg['From'] = mailsender
    msg['To'] = receivers
    msg['Date'] = formatdate()
    # Set Return-Path so that it isn't set (generally incorrectly) for us.
    msg['Return-Path'] = mailsender
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    # now attach the files
    for fn in attach_files:
        with open(fn, 'rb') as fp:
            filedata = fp.read()

        attachment = MIMEApplication(filedata,
                                     'x-zip')  # This may need adjustments!
        attachment['Content-Disposition'] = 'ATTACHMENT; filename="%s"' % \
            path.basename(fn)
        msg.attach(attachment)

    # now comes the final part: send the mail
    mailer = None
    try:
        mailer = smtplib.SMTP(mailserver)
        if debuglevel == 'debug':
            mailer.set_debuglevel(debuglevel)
        mailer.sendmail(mailsender, receiverlist + [mailsender],
                        msg.as_string())
    except Exception as e:
        return [str(e)]
    finally:
        if mailer:
            mailer.quit()
示例#5
0
def test_mailaddress():
    assert mailaddress() == ''
    assert mailaddress('*****@*****.**') == '*****@*****.**'
    assert mailaddress('*****@*****.**') == '*****@*****.**'
    assert mailaddress('*****@*****.**') == '*****@*****.**'
    assert mailaddress(
        '*****@*****.**') == '*****@*****.**'
    assert mailaddress(
        '*****@*****.**') == '*****@*****.**'
    assert mailaddress(
        '[email protected]ömäin.my') == '*****@*****.**'
    assert mailaddress('myaddress@وزارة-الأتصالات.مصر') == \
        '[email protected]'
    assert mailaddress('M. Address <*****@*****.**>'
                       ) == 'M. Address <*****@*****.**>'
    assert mailaddress('M. Address <*****@*****.**> '
                       ) == 'M. Address <*****@*****.**> '
    assert mailaddress('W. Lohstroh, G. Simeoni '
                       '<*****@*****.**>') ==  \
                       'W. Lohstroh, G. Simeoni <*****@*****.**>'
    assert raises(ValueError, mailaddress, 'M. Address [email protected]>')
    assert raises(ValueError, mailaddress, 'M. Address <*****@*****.**')
    assert raises(ValueError, mailaddress, 'my.name.domain.my')
    assert raises(ValueError, mailaddress, '@my.domain')
    assert raises(ValueError, mailaddress, 'my@domain')
    assert raises(ValueError, mailaddress, '[email protected]')
    assert raises(ValueError, mailaddress, 'my@[email protected]')
    assert raises(ValueError, mailaddress, 'my@nonsens@dömain.my')
    assert raises(ValueError, mailaddress,
                  'M. Address <*****@*****.**>,')