⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailmessage.cpp

📁 funambol windows mobile plugin source code, the source code is taken from the funambol site
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/**
 * Format a mailmessage in a RFC2822 string
 */
char * MailMessage::format() {

    // If the message is empty, return null
    if ( empty() ) {
        LOG.debug("MailMessage::format: empty message.");
        return 0;
    }

    StringBuffer ret;

    LOG.debug("MailMessage::format START");

    if ( contentType.empty() ) {
        if ( attachments.size() ) {
            contentType = "multipart/mixed";
        }
        else {
            contentType = body.getMimeType();

            if (headers.size() > 0) {
                StringBuffer *line; int j = 0;
                for (line=(StringBuffer *)headers.front(); line; line=(StringBuffer *)headers.next() ) {
                    if (strstr(line->c_str(), "format=") != 0
                        || strstr(line->c_str(),"reply-type=") != 0 ) {
                            contentType.append("; ");
                            line->replaceAll(";", " ");
                            contentType.append(line->c_str());
                            headers.removeElementAt(j);
                            j--;
                         }
                     j++;
                }
            }

        }
    }
    if ( mimeVersion.empty() ) {
        mimeVersion = "1.0";
    }

    // Add generics headers
    ret.join((ArrayList &)headers, NL);
    // Add parsed headers
    ret += MIMEVERS; ret += mimeVersion; ret += NL;
    ret += MESSAGEID; ret += messageId; ret += NL;
    LOG.debug("MailMessage: From: %s\n", from.c_str());
    ret += FROM; ret += from; ret += NL;
    ret += TO; ret += to; ret += NL;
    if (cc.length() ) {
        ret += CC; ret += cc; ret += NL;
    }
    if (bcc.length() ) {
        ret += BCC; ret += bcc; ret += NL;
    }
    ret += DATE; ret += date.formatRfc822(); ret += NL;
    ret += SUBJECT;

    ret += encodeHeader(subject);

    ret += NL;
    ret += MIMETYPE; ret += contentType; ret+= "; ";
    if (contentType.ifind(MULTIPART) != StringBuffer::npos ){
        if ( boundary.empty() ) {
            generateBoundary(boundary);
        }
        ret += "\n boundary=\""; ret += boundary;
        ret += "\"\n\nThis is a multi-part message in MIME format.\n";
        // Prepare a string with the boundary on a line alone
        StringBuffer bound = "\n--"; bound += boundary;
        // Body
        ret += bound; ret += NL;
        ret += formatBodyPart(body);
        ret += bound;
        // Attachments
        const BodyPart *part;
        for ( part=(const BodyPart *)attachments.front();
              part;
              part=(BodyPart *)attachments.next() ) {
            ret += NL;
            ret += formatBodyPart(*part);
            ret += bound;
        }
        ret += "--\n";
    }
    else {
        // Body
        if(body.getCharset())
            ret += CT_CHARSET; ret += body.getCharset(); ret += NL;
        if( body.getEncoding() )
            ret += ENCODING; ret += body.getEncoding();
        // end of headers
        ret += NL;
        ret += NL;
        ret += body.getContent(); ret += NL;
    }
    LOG.debug("MailMessage::format END");
	return stringdup(ret.c_str());
}


int MailMessage::parse(const char *rfc2822, size_t len) {
    StringBuffer s(rfc2822, len);
    int rc;

    LOG.debug("MailMessage::parse START");

    size_t hdrlen = getHeadersLen(s, newline);

    StringBuffer headers = s.substr(0, hdrlen);    
    StringBuffer rfcbody;

    rc = parseHeaders(headers);
    if(rc)
        return rc;

    if(contentType.ifind(MULTIPART) != StringBuffer::npos) {
        // Multipart message
        rfcbody = s.substr(hdrlen);
        rc= parseBodyParts(rfcbody);
    }
    else {
        // go to the beginning of the body
        hdrlen = hdrlen + strlen(newline) + strlen(newline);
        rfcbody = s.substr(hdrlen);
        body.setMimeType(contentType);
        // FIXME: handle all encodings, not only quoted-printable
        if( strcmp(body.getEncoding(), "quoted-printable") == 0 ) {
            char *decoded = qp_decode( rfcbody );
            body.setContent ( decoded );
            delete [] decoded;
        }
        else if ( strcmp(body.getEncoding(), "base64") == 0 ) {
            char *decoded = NULL;
            size_t len = 0;
            rc = uudecode( rfcbody, &decoded, &len ) ;
            if( !rc ) {
                body.setContent ( decoded );
                delete [] decoded;
            }
        }
        else body.setContent(rfcbody);
    }

    LOG.debug("MailMessage::parse END");
    return rc;
}

StringBuffer decodeHeader(StringBuffer line) {

    if (!line || line.empty()) {
        return line;
    }

    size_t startPos = 0;
    StringBuffer ret;
    StringBuffer charset;
    while( (startPos = line.find("=?", startPos)) != StringBuffer::npos) {
        // Skip the '=?'
        startPos += 2;
        // Find the first '?'
        size_t firstMark = line.find("?", startPos);
        if (firstMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the second '?'
        size_t secondMark = line.find("?", firstMark+1);
        if (secondMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the final '?='
        size_t endPos = line.find("?=", secondMark+1);
        if (endPos == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }

        charset = line.substr(startPos, firstMark - startPos);
        StringBuffer encoding = line.substr(firstMark+1, secondMark - (firstMark + 1));
        StringBuffer text = line.substr(secondMark+1, endPos - (secondMark + 1));

        if (encoding == "Q") {
            // quoted-printable
            text.replaceAll("_", " ");
            char* dec = qp_decode(text);
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }

            ret += dec;
            delete [] dec;
        }
        else if (encoding == "B"){
        // base64
            char* dec = new char[text.length()];
            int len = b64_decode((void *)dec, text);
            dec[len]=0;
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }
            ret += dec;
            delete [] dec;
        }

        startPos = endPos;
    }

    if (ret.length() == 0) {
        ret += line;
    }

    WCHAR* wret = toWideChar(ret, charset);
    ret.set(NULL);
    char* t = toMultibyte(wret);
    ret.set(t);
    if (wret) {delete [] wret;}
    if (t) {delete [] t;}
    return ret;
}


//---------------------------------------------------------- Private Methods

int MailMessage::parseHeaders(StringBuffer &rfcHeaders) {

    ArrayList lines;
    const StringBuffer *line;
    StringBuffer strReceived;
    BOOL receivedExtracted = FALSE;
    LOG.debug("parseHeaders START");

    // Join header parts using \t or 8 blank
    StringBuffer joinlinetab("\t");
    rfcHeaders.replaceAll(joinlinetab, " ");

    StringBuffer joinlinespaces(newline);
    joinlinespaces+=" ";  // 8 blanks

    rfcHeaders.replaceAll(joinlinespaces, " ");

    rfcHeaders.split(lines, newline);

    for ( line=(StringBuffer *)lines.front();
		  line;
		  line=(StringBuffer *)lines.next() ) {

        if( *line == "\r" )
            break;
        // The first empty line marks the end of the header section
        if( line->empty() ){
            break;
        }
        // Process the headers
        bool unknown=false;

        if( line->ifind(TO) == 0 ){
            to = decodeHeader(line->substr(TO_LEN));
        }
        else if( line->ifind(FROM) == 0 ) {
            from = decodeHeader(line->substr(FROM_LEN));
        }
        else if( line->ifind(CC) == 0 ) {
            cc = decodeHeader(line->substr(CC_LEN));
        }
        else if( line->ifind(BCC) == 0 ) {
            bcc = decodeHeader(line->substr(BCC_LEN));
        }
        else if ( line->ifind(DATE) == 0 ) {
            //subjectParsing = FALSE;
            if( date.parseRfc822(line->substr(DATE_LEN)) ) {
                LOG.error("Error parsing date");
                return 500;
            }
        }
        else if( line->ifind(SUBJECT) == 0 ) {

            subject = decodeHeader(line->substr(SUBJECT_LEN));
            LOG.debug("SUBJECT: %s", subject.c_str());
        }
        else if( line->ifind(ENCODING) == 0 ) {  // it is here for single part only
            body.setEncoding(line->substr(ENCODING_LEN));
        }
        else if(line->ifind(MIMEVERS) == 0 ) {
            mimeVersion = line->substr(MIMEVERS_LEN);
        }
        else if(line->ifind(MESSAGEID) == 0 ) {
            messageId = line->substr(MESSAGEID_LEN);
        }
        else if( line->ifind(MIMETYPE) == 0 ) {

            StringBuffer sb = getTokenValue(line, MIMETYPE);

            if (sb.length() > 0)
                contentType = sb;

            sb.reset();
            sb = getTokenValue(line, "boundary=", false);

            if (sb.length() > 0) {
                boundary = sb;
            } else {
                body.setCharset(getTokenValue(line, CT_CHARSET));
            }
            /*

            size_t len = line->find(";") - MIMETYPE_LEN ;
            contentType = line->substr(MIMETYPE_LEN, len);

            // Save boundary for multipart
            size_t begin = line->ifind("boundary=");
            size_t end = StringBuffer::npos;

            if( begin != StringBuffer::npos ) {
                begin += strlen("boundary=\"");
			    end = line->find("\"", begin) ;
			    boundary = line->substr( begin, end-begin );
		    }
            else {
                    begin=line->ifind(CT_CHARSET);
                if( begin != StringBuffer::npos ) {
                    begin += strlen(CT_CHARSET);
                    size_t end = begin;
                    size_t quote = line->find("\"", begin);
                    if (quote != StringBuffer::npos){
                        begin = quote + 1;
                        end = line->find("\"", begin) ;
                    }
                    else {
                        end = line->find(";", begin) ;
                        if (end == StringBuffer::npos) {
                            end = line->find(" ", begin);
                        }
                    }
                    body.setCharset( line->substr( begin, end-begin ) );
                }
            }
            */
	    }
        else if(line->ifind(RECEIVED) == 0) {
            if (!receivedExtracted) {
                strReceived = line->substr(line->rfind(";") );

                if (!strReceived.empty()) {
                    received.parseRfc822(strReceived.substr(2));
                    receivedExtracted = TRUE;
                }
                /*
                while (!strReceived.empty()) {
                    if (received.parseRfc822(strReceived.substr(2)) == 0) {
                        receivedExtracted = TRUE;
                        break;
                    } else {
                        StringBuffer s(line->substr(line->rfind(strReceived.c_str())));
                        strReceived = line->substr(s.rfind(";"));
                    }
                }
                */

            }
        }
        else {
            headers.add(*(StringBuffer *)line);
        }

    }
    // If received was not found, copy send date
    if( received == BasicTime() ){
        received = date;
    }
    LOG.debug("parseHeaders END");

	// FIXME: should check for mandatory headers before return 0
	return 0;
}


int MailMessage::parseBodyParts(StringBuffer &rfcBody) {

    BodyPart part;
    // The boundary is the one defined in the headers preceded by
    // a newline and two hypens
    StringBuffer bound("\n--");
    bound += boundary;

    LOG.debug("parseBodyParts START");

    size_t nextBoundary = rfcBody.find(bound);
    getBodyPart(rfcBody, bound, body, nextBoundary, false);

    if (contentType.ifind("multipart/alternative") == StringBuffer::npos) {
        // If it's not multipart/alternative, get the other parts
        while( getBodyPart(rfcBody, bound, part, nextBoundary, true) ) {
            // some problem in the attachment?
            if( part.getContent() ) {
                attachments.add(part);
            }
            else LOG.error("Empty content in attachment.");
            part = BodyPart();
        }
    }

    LOG.debug("parseBodyParts END");
    return 0;
}

// Return true if the instance is empty (a valid MailMessage must have a valid date that is not
// the default 1/1/1970)
bool MailMessage::empty() {
    return ( this->getDate() == BasicTime() );
}

ArrayElement* MailMessage::clone() {
    return new MailMessage(*this);
}


void MailMessage::setHeaders(const char* chExtraHeaders)
{
    if(chExtraHeaders){
        StringBuffer extraHeaders(chExtraHeaders);
        ArrayList lines;
        extraHeaders.split(headers, "\n");
    }
}

/**
 * The result must be deleted by caller
 */
const char* MailMessage::getHeaders()
{
    if( headers.size() ) {
        StringBuffer buff;
        buff.join(headers, "\n");
        char* strHeaders = stringdup(buff.c_str(), buff.length() -1);
        return strHeaders;
    }
    else return 0;
}

bool MailMessage::operator==(MailMessage& that){
    return (
        this->to == that.to &&
        this->from == that.from &&
        this->cc == that.cc &&
        this->bcc == that.bcc &&
        this->subject == that.subject &&

        this->date == that.date &&
        this->received == that.received &&

        this->contentType == that.contentType &&
        this->boundary == that.boundary &&
        this->mimeVersion == that.mimeVersion &&
        this->messageId == that.messageId
        );
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -