genkgo / mail

Library to send e-mails over different transports and protocols (like SMTP and IMAP) using immutable messages and streams. Also includes SMTP server.
https://mail.readthedocs.io/
Other
402 stars 21 forks source link

How to send a mail using SMTP? #38

Closed k00ni closed 6 years ago

k00ni commented 6 years ago

Hi guys, i would like to use your library, but got stock. Would you mind providing a simple example to send a text mail via SMTP (with given port, username and password)?

I scanned your examples and tests and tried https://qiita.com/mpyw/items/88161f9a809e063823c6, but got lost in all the classes.

Help would be appreciated!

frederikbosch commented 6 years ago

The example from the frontpage - which is not text but html - is not sufficient?

frederikbosch commented 6 years ago

The same example as the frontpage of frontpage of the library but then for text only would be as follows.


// import all the used classes.

$message = (new PlainTextMessage('Hello world'))
    ->withHeader(new Subject('Hello World'))
    ->withHeader(From::fromEmailAddress('from@example.com'))
    ->withHeader(To::fromSingleRecipient('to@example.com', 'name'))
    ->withHeader(Cc::fromSingleRecipient('cc@example.com', 'name'));

$transport = new SmtpTransport(
    ClientFactory::fromString('smtp://user:pass@host/')->newClient(),
    EnvelopeFactory::useExtractedHeader()
);

$transport->send($message);
k00ni commented 6 years ago

My bad, i confused the host information with something like http://example.com, but it seems only example.com, because of the smtp protocol. Will try your example.

@frederikbosch: thanks for the fast reply!

Gave me a hint:

frederikbosch commented 6 years ago

Regarding the SMTP URI. There are three options.

  1. smtp://: Uses port 587 by default, connects insecure and upgrades to a secure connection using STARTTLS. Insecure connections are not allowed. This is recommended.
  2. smtps://: Uses port 465 by default and uses a secure connection directly.
  3. smtp-starttls://: Uses port 25 by default, tries to upgrade using STARTTLS, but allows insecure connection if the upgrade to a secure connection fails.
k00ni commented 6 years ago

Small hint: In case the username contains an @, you need to replace it with %40. (Info from here)

Your scripts work like a charm, after i got them setup. Its a little bit confusing with all the classes, but i get used to it. Thanks.