Giter Site home page Giter Site logo

laminas / laminas-mime Goto Github PK

View Code? Open in Web Editor NEW
29.0 19.0 23.0 1.74 MB

Create and parse MIME messages and parts

Home Page: https://docs.laminas.dev/laminas-mime/

License: BSD 3-Clause "New" or "Revised" License

PHP 99.83% Shell 0.17%
hacktoberfest security-updates-only mime-message

laminas-mime's Introduction

laminas-mime

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

This package is considered feature-complete, and is now in security-only maintenance mode, following a decision by the Technical Steering Committee. If you have a security issue, please follow our security reporting guidelines. If you wish to take on the role of maintainer, please nominate yourself

If you are looking for an actively maintained package alternative, we recommend:

Build Status

Laminas\Mime is a support class for handling multipart MIME messages. It is used by Laminas\Mail and Laminas\Mime\Message and may be used by applications requiring MIME support.

Installation

Run the following to install this library:

$ composer require laminas/laminas-mime

Documentation

Browse the documentation online at https://docs.laminas.dev/laminas-mime/

Support

laminas-mime's People

Contributors

akrabat avatar bakura10 avatar blanchonvincent avatar dasprid avatar davidwindell avatar evandotpro avatar ezimuel avatar freeaqingme avatar jonathanmaron avatar keradus avatar kokspflanze avatar koopzington avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mpinkston avatar mwillbanks avatar ocramius avatar padraic avatar prolic avatar ralphschindler avatar samsonasik avatar sgehrig avatar thinkscape avatar thomasweidner avatar vahid-sohrabloo avatar veewee avatar wdalmut avatar weierophinney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laminas-mime's Issues

Why is that mime\part\setFileName does not encode

Bug Report

Q A
Version(s) 2.8.0

Summary

Current behavior

the $filename is passed as-is:

How to reproduce

<?php

use Laminas\Mime;

require __DIR__ . '/vendor/autoload.php';

$part = new Mime\Part();
$part->setDisposition(Mime\Mime::DISPOSITION_ATTACHMENT);
$part->setFileName('Testá.xlsx');
$part->setContent('a');
print_r($part->getHeaders());
Content-Type: application/octet-stream
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="Testá.xlsx"

Expected behavior

The getHeaders() method should encode using *= or *1*= or at least quoted-printable.

refs:

MimePart is inefficient when handling in-memory data

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7471
User: @ddxor
Created On: 2015-04-30T07:55:22Z
Updated At: 2015-11-06T21:30:58Z
Body
MimePart requires that I pass it a type of resource as part of the object construct.

In my scenario I have just generated a PDF which I want to attach to an e-mail. Using MimePart I have to first write that PDF to disk, get a resource for it, pass that to MimePart which will then read it back from disk again.

This is wasteful IO. I should be able to pass MimePart a string and encoding type directly.


Comment

User: @Ocramius
Created On: 2015-04-30T07:58:52Z
Updated At: 2015-04-30T07:58:52Z
Body
You can create in-memory resources...
On Apr 30, 2015 08:55, "James Anslow" [email protected] wrote:

MimePart requires that I pass it a type of resource as part of the object
construct.

In my scenario I have just generated a PDF which I want to attach to an
e-mail. Using MimePart I have to first write that PDF to disk, get a
resource for it, pass that to MimePart which will then read it back from
disk again.

This is wasteful IO. I should be able to pass MimePart a string and
encoding type directly.


Reply to this email directly or view it on GitHub
zendframework/zendframework#7471.


Comment

User: @ddxor
Created On: 2015-04-30T08:52:14Z
Updated At: 2015-04-30T08:52:14Z
Body
MimePart already does what I want it to internally, just not as an option during construct. Even if I construct an in-memory resource I am still having to modify memory and waste resources doing so.



Originally posted by @GeeH at zendframework/zend-mime#16

\Laminas\Mime\Decode::decodeQuotedPrintable() doesn't seem to do what its name suggests

Bug Report

Q A
Version(s) 2.12.0

Summary

I can successfully encode a string using \Laminas\Mime\Mime::encodeQuotedPrintable(), however when I use \Laminas\Mime\Decode::decodeQuotedPrintable(), I don't seem to get the expected result.

Current behavior

Passing =0A into \Laminas\Mime\Decode::decodeQuotedPrintable() does not result in a newline character, but instead gives back the same input string.

How to reproduce

<?php

require_once __DIR__ . '/vendor/autoload.php';

$text = "This string spans\ntwo lines.";
$encoded = \Laminas\Mime\Mime::encodeQuotedPrintable($text);
$decoded = \Laminas\Mime\Decode::decodeQuotedPrintable($encoded);

var_dump($text, $encoded, $decoded, $text === $decoded);
string(28) "This string spans
two lines."
string(30) "This string spans=0Atwo lines."
string(30) "This string spans=0Atwo lines."
bool(false)

Expected behavior

string(28) "This string spans
two lines."
string(30) "This string spans=0Atwo lines."
string(28) "This string spans
two lines."
bool(true)

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Mime::encodeQuotedPrintableHeader breaks Zend_Mail's parsing if encoding is needed and there are multiple recipients

The following code illustrates the weirdness:

<?php

require_once __DIR__.'/vendor/autoload.php';
use Zend\Mime\Mime;

$str = '=?iso-8859-1?Q?Jorgen?= <[email protected]>,=?iso-8859-1?Q?Schmorgen?= <[email protected]>';
$header = iconv_mime_decode($str);

$encoded = Mime::encodeQuotedPrintableHeader($header, 'UTF-8', 78, "\r\n");
echo $encoded;

The output:

=?UTF-8?Q?Jorgen=20<[email protected]>,Schmorgen=20<[email protected]>?=

This is a problem now that zend-mail explodes the whole encoded string on a comma to due to this:
zendframework/zend-mail#44
Which results in the prefix and suffix being split up, breaking the parsing of the header.

The RFCs don't seem to be clear about whether the header field separator is allowed in the middle of a quoted-printable string, but do say that it should only be used if necessary for a given token.


Originally posted by @ftzdomino at zendframework/zend-mime#12

Attachments with longs names are not being processed

Bug Report

Q A
Version(s) 2.10.x

Summary

Attachments with filenames, longer than 76 char symbols, are not being processed.

Current behavior

Currently, Laminas\Mail successfully identifies long names and successfully splits them into multiple variables in \Laminas\Mail\Header\ContentDisposition::getFieldValue().
However, the multiple variables do not get recognized in Laminas\Mime\Decode::splitHeaderField() due to this check
strcasecmp($name, $wantedPart)
i.e. it compares "filename*0" with "filename"

How to reproduce

Try to process an email with an attachment with long name, for example
"This_______________________________________________________is____________________long__________________________________name.txt"

Expected behavior

It should not compare with strcasecmp, but rather with a regex. Then if it is a multiple value, it should concatenate the values

Suggested fix

    $fullField = [];
    if ($wantedPart) {
        foreach ($matches[1] as $key => $name) {

            if (!preg_match('/' . preg_quote($wantedPart) . "(\*[0-9])*" . '/', $name)) { //support multiname
                continue;
            }

            $val = $matches[2][$key][0] != '"' ? $matches[2][$key] : substr($matches[2][$key], 1, -1);

            // if name and wantedPart doees not match fully(they have matched above in the regex),
            // it means that we have multiple values
            if (strcasecmp($name, $wantedPart) && gettype($val) === 'string') {
                $fullField[$wantedPart] .= $val;
            } else {// name and wantedPart match
                return $val;
            }

        }
        return $fullField[$wantedPart] ?: null;
    }

Attachments can not be seperated from mail body correctly

I try to get Attachments from a message but i allways get error:

2016-12-30T15:46:09+00:00 CRIT (2): Something went wrong: Line "Received: (qmail 5233 invoked from network); 30 Dec 2016 16:46:09 +0100
X-Fcrdns: Yes
Received: from xxxxxxxxx.adsl.highway.telekom.at (HELO [xxx.xxx.xxx.xxx]) (xxx.xxx.xxx.xxx)
(smtp-auth username [email protected], mechanism plain)
by server.de (qpsmtpd/0.92) with (ECDHE-RSA-AES256-SHA encrypted) ESMTPSA; Fri, 30 Dec 2016 16:46:09 +0100
To: [email protected]
From: sssssd ddddn [email protected]
Subject: testmail
Organization: ddddddddddddddddddd
Message-ID: 5114d274-dde3-2ca5-6c9d-3bd59f59065a@ddddddddd
Date: Fri, 30 Dec 2016 16:46:04 +0100
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Thunderbird/45.5.1
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="------------3FE86778A6885A966DF16AC3"
X-User-Auth: Auth by [email protected] through xxx.xxx.xxx.xxx" does not match header format!

It's identical to zendframework/zendframework#2606 which is closed.

$rawMsg = preg_replace('~\R~u', "\r\n", $rawMsg);

seems to be a quickfix, the mail can then be parsed, but the filenames cannot be read and are empty on the attachment object.

This is my sourcecode to split the message which comes from stdin.

        $rawMsg = preg_replace('~\R~u', "\r\n", $rawMsg);
        $message = new \Zend\Mail\Message();
        $headers = null;
        $content = null;

        \Zend\Mime\Decode::splitMessage($rawMsg, $headers, $content, \Zend\Mail\Headers::EOL);     
        $boundary = $headers->get('contenttype')->getParameter('boundary');
        $mimeMsg = \Zend\Mime\Message::createFromMessage($content, $boundary);
        $message->setHeaders($headers);
        $message->setBody($mimeMsg);
        $attachmentsDesc=$mimeMsg->getParts();
        $fileManager=new FileManager();
        
        foreach($attachmentsDesc as $attachment)
        {
            $this->log->debug($attachment->type);  // this property  holds content type, line break AND name 
            $this->log->debug($attachment->filename); // this is empty
       //     $fileData=$fileManager->storeStreamToInbox(base64_decode($attachment->getContent()), $attachment->filename);
            
            $this->log->debug("file created");
        }

Originally posted by @SevenbitsIt at zendframework/zend-mime#23

Adding a duplicate part to a message should not be permitted

Bug Report

Q A
Version(s) 2.9.0

Summary

The change to use a strict comparison in \Laminas\Mime\Message::addPart (if ($part === $row) {) means that the given $part can contain the exact same data as the existing $row, but an exception will only be throw if they're the same instance. It shouldn't be possible to add two parts containing identical data.

How to reproduce

$part1 = (new \Laminas\Mime\Part('DATA'))->setId('ID');
$part2 = (new \Laminas\Mime\Part('DATA'))->setId('ID');

$message = new \Laminas\Mime\Message();
$message->addPart($part1);
$message->addPart($part2); // should throw \Laminas\Mime\Exception\InvalidArgumentException with message 'Provided part ID already defined.'

Workaround

For now, this can easily be worked around by doing something like:

$message = new \Laminas\Mime\Message();
$message->addPart($part1);

if (in_array($part1, $message->getParts())) {
    return;
}

$message->addPart($part2); 

Cannot get attachment filename using createFromMessage to parse eml

Message::createFromMessage cannot get attachment filename in parts

How to reproduce

create test.eml

Content-Type: application/text; name=hello.txt
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=hello.txt

aGVsbG8gd29ybGQh

php

use Laminas\Mime\Message;
$message = Message::createFromMessage(file_get_contents('test.eml');
print_r($message->getParts());

echo $message->getParts()[0]->getFileName();  // empty output

output

Array
(
    [0] => Laminas\Mime\Part Object
        (
            [type] => application/text;
 name="hello.txt"
            [encoding] => base64
            [id] =>
            [disposition] => attachment; filename="hello.txt"
            [filename] =>
            [description] =>
            [charset] =>
            [boundary] =>
            [location] =>
            [language] =>
            [content:protected] => hello world!
            [isStream:protected] =>
            [filters:protected] => Array
                (
                )

        )

)

Expected behavior

Array
(
    [0] => Laminas\Mime\Part Object
        (
            [type] => application/text;
 name="hello.txt"
            [encoding] => base64
            [id] =>
            [disposition] => attachment
            [filename] => hello.txt
            [description] =>
            [charset] =>
            [boundary] =>
            [location] =>
            [language] =>
            [content:protected] => hello world!
            [isStream:protected] =>
            [filters:protected] => Array
                (
                )

        )

)

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a .psalm.xml.dist in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

A logical bug occurs while splitting header field

According to https://tools.ietf.org/html/rfc5322, the following email address example is completely ok:

"Some Name" <[email protected]>

But when you pass this value to Zend\Mime\Decoder::splitHeaderField(); it returns a wrong value because of a logical bug in the code (Line #181, the condition is not correct for all cases):

Expected results

"Some Name" <[email protected]>

Actual results

"Some Name" <[email protected]

So, in the actual result, the last character is missing.


I would like to create a merge request with valid tests if you think this should be fixed.


Originally posted by @ozanakman at zendframework/zend-mime#40

MTOM messages with binary message-parts mallformed after splitMime

After the splitMime function the content of a message containing a messagepart in binary (using with MTOM xop:Include) will get malformed. In my case a PDF becomes pretty much unreadable (still valid PDF but all images and markup are broken)

I'm pretty sure it's this line causing the problem
https://github.com/zendframework/zend-mime/blob/master/src/Decode.php#L30

It discards any \r character in the entire message, changing the content of the binary attachment and breaking it.


Originally posted by @mannes at zendframework/zend-mime#24

laminas/laminas-mail should be a requirement, not only require-dev

Bug Report

Q A
Version(s) 2.7.2

Summary

Current behavior

In Decode.php line 150:

  Attempted to load class "Headers" from namespace "Laminas\Mail".
  Did you forget a "use" statement for "Symfony\Component\Mime\Header\Headers"?

laminas/laminas-mail should be a dependency of this library

How to reproduce

$message = Laminas\Mime\Message::createFromString('foo');

Expected behavior

No error, because of installed dependency:
Screenshot 2020-01-27 13 45 52

Composer info

Screenshot 2020-01-27 13 46 51

Colon(:) not encoded in Mime class encodeQuotedPrintableHeader method

I am using laminas-mail package for creating email messages in my project. laminas-mail package uses this package's Mime class encodeQuotedPrintableHeader method for encoding non ASCII header fields. But unlike other characters colon(:) is not encoded(replaced with =3A), which causes mail sender client(Amazon SES) in my case to reject the message. I suppose there will be also problem with other RFC 5322 special characters. So can you please encode these special characters like it is done on Mime::encodeQuotedPrintableHeader method line 204
$str = str_replace(['?', ',', ' ', '_'], ['=3F', '=2C', '=20', '=5F'], $str);

Random spaces or broken characters in html mails with a lot of content

Hello,

we encountered an issue when sending multipart emails (html and text) with a lot of content.
There either random spaces inside the source code of the mail or broken characters because of invalid character entities.

Since things are working fine when we use the swiftmailer, we could get an idea where the error could be.

According to the RFC 2045 (search for "76"), you are doing a a hard line break instead of a soft line break after 76 characters (see Zend\Mime\Part and search for 76).
Swiftmailer is handling this 76 character limitation totally differently.
Since this is not an easy topic my thoughts are no having any kind of offense inside. My Intension is to put you into the right direction.

How can you reproduce this issue?
Send a multipart email with a lot of content in html and text.

Best regards,
Stev

[Update]
It would be cool if you could put the link to the RFC 2045 as close to the code as possible.
It took me a while to get the sense behind this "76" number when I had a look into the code.

What about this way?

    'line-length'      => 76, //@link** http://www.faqs.org/rfcs/rfc2045.html

Or put the "76" as constant on top and add the link as comment?


Originally posted by @stevleibelt at zendframework/zend-mime#29

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.