EzDevInfo.com

swiftmailer

Comprehensive mailing tools for PHP Powerful component based mailing library for PHP – Swift Mailer

trying to send mail using swift mailer, gmail smtp, php

Here is my code:

<?php
require_once 'Swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465)
  ->setUsername('me@ff.com')
  ->setPassword('pass');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
  ->setFrom(array('me@ff.com' => 'MY NAME'))
  ->setTo(array('you@ss.com' => 'YOU'))
  ->setBody('This is the text of the mail send by Swift using SMTP transport.');
//$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png');  
//$message->attach($attachment);
$numSent = $mailer->send($message);
printf("Sent %d messages\n", $numSent);
?>

AFter RUNNING GOT THIS ERROR...

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Expected response code 220 but got code "", with message ""' in /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php:406

Stack trace: 
#0 /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(299): Swift_Transport_AbstractSmtpTransport->_assertResponseCode('', Array) 
#1 /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(107): Swift_Transport_AbstractSmtpTransport->_readGreeting() 
#2 /home/sitenyou/public_html/Swift/lib/classes/Swift/Mailer.php(74): Swift_Transport_AbstractSmtpTransport->start() 
#3 /home/sitenyou/public_html/sgmail.php(16): Swift_Mailer->send(Object(Swift_Message)) 
#4 {main} thrown in /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php on line 406

Source: (StackOverflow)

HTML vs Plain text as body in email

When creating a Swift_Message you can have both a plain text and an html version of the email. You set one as the body, and then you add the other one as a part.

What is the difference if I set the HTML version as body and plain text as part, and the other way around?

$html_as_body = Swift_Message::newInstance()
    ->setSubject($subject)
    ->setBody($html, 'text/html')
    ->addPart($plain, 'text/plain');

$plain_as_body = Swift_Message::newInstance()
    ->setSubject($subject)
    ->setBody($plain, 'text/plain')
    ->addPart($html, 'text/html');

And by difference, I mean what kind of difference will it have in email readers and such?


Source: (StackOverflow)

Advertisements

How to use the swiftMailer in Yii2

I can't finally understand how to use the swiftMailer extension in Yii2. Judging by that on this subject I didn't find questions, the task is trivial, but up to the end I couldn't understand.

There are examples which don't describe in more detail all cycle of sending the letter or I don't understand something :(

Setup

    return [
    //....
   'components' => [
    ......
    'mail' => [
      'class' => 'yii\swiftmailer\Mailer',
      'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'localhost',
        'username' => 'username',
        'password' => 'password',
        'port' => '587',
        'encryption' => 'tls',
      ],
    ],
  ]
];

Send

Yii::$app->mail->compose()
->setTo($toEmail)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();

I want will receive a concrete working example. Thank you.

P.S. I adjusted domain records MX, DKIM, SPF added.

UPD (some answer):

E-mail which is passed in "From" field, it is put down by default in the field of "Return-path", has to be the existing address. Some providers don't allow sending mail from nonexistent email addresses.


Source: (StackOverflow)

PHP and Gmail spam filter

I've spent hours trying to solve this, so I look very much forward to any suggestions or answers, whatsoever.

I have made a mail-system, that first generated a PDF-file (using the FPDF-library), whereafter it sent the PDF-file as an attachment with PHP's Swiftmailer. This email was sent out to 130 people who signed up. But it landed in the spam-filter for almost everybody. I tried adjusting SwiftMailers header-settings, but without any luck. The mails still ended up in the spam-filter - even for mails that I haven't sent to before (I tested with my friends Gmail). This was my previous setup:

function sendMailEt($toEmail, $toName, $invoiceNumber){

require_once($_SERVER[DOCUMENT_ROOT] . '/includes/lib/swift_required.php');

$transport = Swift_SmtpTransport::newInstance('mailout.one.com', 25)
  ->setUsername('EMAIL-ACCOUNT1@THE-DOMAIN.DK')
  ->setPassword('THE-PASSWORD')
  ;    

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Fra Company name')
      ->setSubject('Thanks for signing up - Company name')
  ->setFrom(array('SAME-EMAIL-AS-SEEN-ABOVE@THE-DOMAIN.DK' => 'Company name'))
  ->setTo(array($toEmail => $toName))
      ->setBody('A brief body, that explains that this is an invoice and that it has to be paid within 5 days. (written in danish)')
      ->addPart('A brief body, that explains that this is an invoice and that it has to be paid within 5 days. (written in danish)', 'text/html')

   ->attach(Swift_Attachment::fromPath($_SERVER['DOCUMENT_ROOT'].'/URL-TO-THE-PDF-FILE.pdf'))
  ;

$result = $mailer->send($message);
}

Since I couldn't change the header, then I changed tactics. I started using SwiftMailer, because another thread was advicing to use an SMTP-mailer. I also used it, because I could attach the invoice as a PDF-file. So I then changed the tactic, where I just send out the emails with PHP's mail()-function. I would then just link back to the invoice ( http://www.company-domain-name.dk/invoice/base64_encoded-name.pdf ). I would then just write the header myself. I've read a numerous amount of forums about what headers should include, but they all wrote different things. So I tried a few of them and sent a test out to myself and some of my friends, who haven't 'heard' from or recieved emails from this company as well. I also tried to let myself inspire by MailChimps mail-header, since they must have tried all sort of different stuff, to bypass spam-filters. I ended up with this:

 $headers = "Reply-To: Company name <UNUSED-EMAIL-ACCOUNT-FROM-DOMAIN@DOMAIN-NAME.DK>\r\n"; 
 $headers .= "Return-Path: Company name <UNUSED-EMAIL-ACCOUNT-FROM-DOMAIN@DOMAIN-NAME.DK>\r\n"; 
 $headers .= "From: Message from Company name <UNUSED-EMAIL-ACCOUNT-FROM-DOMAIN@DOMAIN-NAME.DK>\r\n"; 
 $headers .= "MIME-Version: 1.0\r\n";
 $headers .= "Sender: Message from Company name <UNUSED-EMAIL-ACCOUNT-FROM-DOMAIN@DOMAIN-NAME.DK>\r\n";
 $headers .= "Content-type: text/plain; charset=\"utf-8\"; \r\n";
 $headers .= "X-Mailer: PHP". phpversion() ."\r\n";

And then I send the mail like this:

mail($toName . '<'.$toEmail.'>', utf8_decode('Faktura på depositumet'), utf8_decode($someMessage), $headers);

The webspace is with one.com, so I can't use PHPmailer (since that has to be installed, and that can't be done on one.com's servers). And I can't define a SPF with One.com.

All I want to do, is to be able to send a simple e-mail with PHP, containing some text and a link to the domain, that doesn't go in the frick'n spam-filter :-). That's all I want.

Ok. Here are my trouble-shooting: 1) With the PHP-mail() header, then I can define who the e-mail is from. If I previously have sent an e-mail from account1@domain-name.dk and that gets caught in the spam-filter and the header for this email was bad/screwed up. Would it then work to just fix the header, or will that email-account have been blacklisted as spam. 2) And can a whole domain-name be blacklisted (where it'll go to spam regardless of if the mail is sent from account1@domain-name.dk or account2@domain-name.dk)? 3) Is it possible, that the account info@domain-name.dk (the account that sent out all the mails that got marked as spam), that it has been put in the spam-filter so many times, that all Gmail-accounts have to manually go and 'Unmark it as spam', before it lands in the inbox (even if they haven't recieved mails from that account before). I mean, does Gmail spam-settings for each account individually or does it take everything into account (even from accounts that aren't linked in any way)?

EDIT... (Addition) ...

Ok... I have now tried a number of things. I tried adding LoneWolfPR's returnpath, like recommended, and it didn't help. I contacted One.com (the hosting company), and confirmed with them, that it isn't possible to set a SPF-record or a DKIM-record. It still isn't. Yet, I can't believe, that it isn't possible to send a simple e-mail from PHP til a Gmail-account, without having to fight with all those records, in order for it to pass the spam-filter. I can also see in the mail-header, that there is set some sort of SPF-record (it's set to neutral). So I decided to show you what my current email-header looked like:

Delivered-To: NEWLY-CREATED-GMAIL-ACCOUNT@gmail.com
Received: by 10.76.75.104 with SMTP id b8csp48728oaw;
        Sat, 16 Mar 2013 17:32:56 -0700 (PDT)
X-Received: by 10.152.116.45 with SMTP id jt13mr7897860lab.0.1363480376067;
        Sat, 16 Mar 2013 17:32:56 -0700 (PDT)
Return-Path: <XXX111@lyobeachcamp.dk>
Received: from mail-out2.b-one.net (mail-out2.one.com. [91.198.169.19])
        by mx.google.com with ESMTP id p10si4637427lbb.120.2013.03.16.17.32.55;
        Sat, 16 Mar 2013 17:32:55 -0700 (PDT)
Received-SPF: neutral (google.com: 91.198.169.19 is neither permitted nor denied by best guess record for domain of XXX111@lyobeachcamp.dk) client-ip=91.198.169.19;
Authentication-Results: mx.google.com;
       spf=neutral (google.com: 91.198.169.19 is neither permitted nor denied by best guess record for domain of XXX111@lyobeachcamp.dk) smtp.mail=XXX111@lyobeachcamp.dk
Date: Sat, 16 Mar 2013 17:32:55 -0700 (PDT)
Message-Id: <51450f37.6a0b700a.6239.5dbcSMTPIN_ADDED_MISSING@mx.google.com>
Received: from localhost.localdomain (srv18.one.com [193.202.110.18])
    by mail-out2.b-one.net (Postfix) with ESMTP id F3D0B10365
    for <NEWLY-CREATED-GMAIL-ACCOUNT@gmail.com>; Sun, 17 Mar 2013 01:32:53 +0100 (CET)
Received: from 85.218.159.219 by www.lyobeachcamp.dk via URL_TO_THE_SCRIPT.php with HTTP; Sun, 17 Mar 2013 00:32:53 +0000
To: RECIEVERS_NAME <NEWLY-CREATED-GMAIL-ACCOUNT@gmail.com>
Subject: Faktura på depositumet
X-PHP-Originating-Script: 87486:NAME-OF-THE-SCRIPT-THE-E-MAIL-WAS-SENT-FROM.php
Reply-To: Lyø Beach Camp <XXX111@lyobeachcamp.dk>
From: Besked fra Lyø Beach Camp <XXX111@lyobeachcamp.dk>
MIME-Version: 1.0
Sender: Besked fra Lyø Beach Camp <XXX111@lyobeachcamp.dk>
Content-type: text/plain; charset="utf-8"; 
X-Mailer: PHP5.3.21

Hej E-MAIL-OWNER-NAME. 

 Her er et link til din faktura 

 http://www.lyobeachcamp.dk/ENCRYPTED_URL_TO_INVOICE.pdf . 

 Du skal betale denne faktura indenfor den næste 5 dage. Senere hen vil du modtage en
 faktura på restbeløbet. Du vil så modtage dit rejsebevis kort før afrejse-datoen 
(omkring to ugers tid før). Vi kan desværre ikke melde de eksate flytider ud, før da. 
Du kan dog følge med i de midlertidige flytider som vi har på 
http://www.lyobeachcamp.dk/flytider . 


Med venlig hilsen 

Lyø Beach Camp 

Web: http://www.lyobeachcamp.dk 

Mail: Hvis der er noget, så er du altid velkommen til at skrive os en mail på 
XXX222@lyobeachcamp.dk

XXX111@lyobeachcamp.dk and XXX222@lyobeachcamp.dk are two different e-mail accounts.

I considered to setup an 'unsubscribe'-link, with a link to a website with a form, but I didn't believe that approach. I mean - invoices are sent all the time, with e-mails. And why should you be able to unsubscribe an invoice?! Since that made so far from sense in my head, then I only tried it for about 20 minutes, and then I spent my time trying other things.

EDIT VERSION 2... (Addition number 2)

For those, who have found this thread. I still haven't found a solution for this problem. It feels like that I've tried everything. My next step will be: - Look into SendGrid (even though the cheapest price is 10 dollars per month, so that's quite an expensive solution, just to send mails that doesn't get caught by a spam filter). - Look into an alternative solution to sending mails from an external source (somewhere, where a SPF-record and all that can be set). - Maybe look into using MailChimps API to send out the mails, even though it seems like, that it can't be used to send single mails to single recipients, which is what this thread is about).

I must say, that this issue is started to cause quite a few grey hairs on my head. It's a f*cking sh*t problem, pardon my french! Any suggestions are really appreciated. Even just a point in the right direction would be cool.


Source: (StackOverflow)

Tracking email bounces, opens, clicks

I found How do you make sure email you send programmatically is not automatically marked as spam? to (hopefully) be a solid guide to avoiding being marked as spam. Are there any other important tips/suggestions?

How do I track bounces,opens,clicks? These are features found in paid services like Mail Chimp and Campaign Monitor.


Source: (StackOverflow)

Symfony2 Swiftmailer Not Sending

I am having trouble sending emails with symfony2 and swiftmailer. I am also a bit lost on how to debug this issue. Below is the code. First I am creating a form to display. On submit (request->method == post) I then try to send the email. I am getting no errors and it is taking me to the thankyou page, however, I am not receiving any email. I have tested on prod and dev. In dev I have opened the profiler after submission and it shows 0 emails. Any help is appreciated! Thanks!

public function contactAction(Request $request)
{
    $defaultData = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message');
    $form = $this->createFormBuilder($defaultData)
        ->add('name', 'text')
        ->add('email', 'email')
        ->add('subject', 'text')
        ->add('message', 'textarea')
        ->getForm();

    if($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        $data = $form->getData();
        $message = \Swift_Message::newInstance()
            ->setSubject($data['subject'])
            ->setFrom('no-reply@mysite.com')
            ->setTo('email@mysite.com')
            ->setBody($this->renderView('AdaptiveSiteBundle:Default:email.txt.twig', array('name' => $data['name'], 'message' => $data['message'])))
        ;
        $this->get('mailer')->send($message);

        return $this->redirect($this->generateUrl('thankyou'));
    } 

    return array("form" => $form->createView());
}

Source: (StackOverflow)

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

When I send an email with the PHP Swift mailer to this server: smtp.exchange.example.com like this:

// Load transport
$this->transport =
    Swift_SmtpTransport::newInstance(
       self::$config->hostname,
       self::$config->port
    )
    ->setUsername(self::$config->username)
    ->setPassword(self::$config->password)
    ;

// Load mailer
$this->mailer = Swift_Mailer::newInstance($this->transport);

// Initialize message
$this->message = Swift_Message::newInstance();

// From
$this->message->setFrom(self::$config->from);

// Set message etc. ...

// Send
$this->mailer->send($this->message);

I get a strange error back:

Failed to authenticate on SMTP server with username "user@example.com" using 2 possible authenticators

I know for sure that the login-info is correct.


Source: (StackOverflow)

Unable to send e-mail from within custom Symfony2 command but can from elsewhere in app

I have written a custom console command to query my database, produce a report and e-mail it to an address; however I can not seem to successfully send the e-mail. I can send e-mail fine from within normal controllers elsewhere within my application, and I can also send it from within my console command if I manually create and configure a Swift_Mailer instance and not get it via the container.

Here is a stripped down version of my console command:

<?php

namespace Foo\ReportBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ExpiryCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('report:expiry')
            ->setDescription('Compile and send e-mail listing imminent expiries');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /* ... */
        $message = \Swift_Message::newInstance()
            ->setSubject('Expiry report')
            ->setFrom('DoNotReply@domain.com')
            ->setTo('recipient@domain.com')
            ->setBody($body);

        $mailer = $this->getContainer()->get('mailer');

/*      This works...
        $transport = \Swift_SmtpTransport::newInstance('smtp.domain.com', 25)
            ->setUsername('username')
            ->setPassword('password');
        $mailer = \Swift_Mailer::newInstance($transport);
*/
        $result = $mailer->send($message);
        $output->writeln($result);
    }
}

Swiftmailer is configured to send via SMTP within my app/config/config.yml file (delivery_address: dev@domain.com is also set in app/config/config_dev.yml):

swiftmailer:
    transport: smtp
    host: smtp.domain.com
    username: username
    password: password
    spool:
        type: memory

When running the command, it prints 1 to the command line, which I assume it means it was successful. However I'm monitoring my mail server's logs at the same time, and it's not even connecting.

To confirm that my configuration was being loaded into the mailer, I changed the spool from memory to file and messages are being spooled to the file system when running the command and I can successfully flush the spool on the command line with php app/console swiftmailer:spool:send.

Does anyone have any ideas as to what's happening here, or any suggestions as to how I can debug it further? Nothing is appearing in my app/logs/dev.log file. I'm using Symfony 2.1.3-DEV.


Source: (StackOverflow)

How to close Smtp connection in SwiftMailer

I use SwiftMailer to send emails from a gearman worker process. I'm using the Swift_SmtpTransport class to send emails.

The problem is that if this worker process stays idle for sometime, the SwiftMailer smtp connection times out. Now when the next job arrives, SwiftMailer fails to send emails as the connection has been timed out.

Ideally, I would want to close the smtp connection after every job. I'm unable to locate a api in the class which does this specifically. Neither does unset() object works since this is a static class.


Source: (StackOverflow)

Sending group messages using send grid, gives 500 Internal Server Error

I want to send group messages using send grid. My group have 100 members.When I send a group message, 50 to 80 messages are delivered and then it shows a blank page as:

NetworkError: 500 Internal Server Error

My Code is,

set_time_limit (0);
$usernames = 'username'; // Must be changed to your username
$passwords = 'password';  // Must be changed to your password
// Create new swift connection and authenticate
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 25);
$transport ->setUsername($usernames);
$transport ->setPassword($passwords);
$swift = Swift_Mailer::newInstance($transport);
// Create a message (subject)
$message = new Swift_Message($subject);
// add SMTPAPI header to the message
$headers = $message->getHeaders();
$headers->addTextHeader('X-SMTPAPI', $hdr->asJSON());
// attach the body of the email
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
if ($recipients = $swift->send($message,$failures)){
    $message= 'Message sent';
}else{
    $message= "Something went wrong -  message not sent, please try later";
}

asJSON:

{
  "to": [
    ""
  ],
  "sub": {
    "-name-": [
      "anu"
    ],
    "-time-": [
      "12 PM"
    ]
  },
  "category": "initial",
  "filters": {
    "footer": {
      "settings": {
        "enable": 1,
        "text\/plain": "Thank you "
      }
    }
  }
}

Source: (StackOverflow)

Can I use Amazon's SES with Symfony2 and the Swiftmailer Bundle?

I'm hosting a site on Amazon's ec2 running a 64-bit version of CentOS.

The site has a simple Contact Us form that needs to send an email to several addresses when submitted (pretty basic).

Has anyone used Amazon's SES with Symfony2 and the Swiftmailer Bundle? And if so, do you recommend using SES or a more traditional email server for this type of task?


Source: (StackOverflow)

Multiple Attachments with Swiftmailer

I'm creating a form that allows multiple files to be uploaded. The form field values and attachments are then to be emailed to certain address. I'm using Swiftmailer to generate these emails. I know how to attach a file with Swiftmailer, but I don't know how to attach multiple files. Does anybody know whether this is possible using Swiftmailer?


Source: (StackOverflow)

Swift_Mailer + symfony UTF-8

I have an issue with Swift_Mailer in Symfony. I am sending e-mail messages in French which contain a lot of "à é è" characters. At first when i tried sending these characters came out fine in my email-client, but in my colleague's email-client they didn't.

So I put the text for the mail through a utf8_encode function and tried again. Now it is vica-versa. It shows fine in my email-client, but screwed up in my colleague's.

What is the best way to solve these e-mail UTF-8 issues with Swift_Mailer in Symfony?


Source: (StackOverflow)

How secure can a PHP-driven HTML contact form using Swiftmailer be?

I have a PHP driven HTML contact form on my site. Currently I use the PHP mail() function. Because of that I have to do many user input validation to avoid email header injection attacks. I think I'm secure, but I probably forgot something and I want to move to a solid PHP email library. The library I selected is Swiftmailer.

Now I want to check if Swiftmailer address the following:

  1. Removes or escape < and > characters in sender names.
  2. Removes newlines (\n, \r\n...) from sender names.
  3. Removes or escape newlines from email subject.
  4. Normalize newlines in message body (the content of the email). As per the PHP docs, \n should be used in content and \r\n as email headers separator.

PS: I tried to contact the Swiftmailer team with my questions without success so I'm trying here.

Edit:

I did some test cases with Swiftmailer and this is what I found so far:

  1. When you have a < or > in the name of a sender, you get a Undeliverable email error mail. This can somewhat lead in a DOS attack of your mail server (maybe I'm wrong). Is this normal?!
  2. The newlines are escaped so the injection attack fails.
  3. The newlines are escaped so the injection attack fails.
  4. Tested but I'm unable to see what Swiftmailer do (if it does something). So I'm still in the dark here.

Can someone clarify #1 and #4 for me? I'm not sure if it's normal behavior...


Source: (StackOverflow)

Sending email using php, gmail, and swiftmailer causes SSL-related error

Here is my PHP code:

function SendCookieToTheMail()
{
    require_once 'swift-mailer/lib/swift_required.php';
    //Create the Transport
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com')
      ->setPort(465)
      ->setEncryption('ssl')
      ->setUsername('007@gmail.com')
      ->setPassword('123')
      ;

    //Create the Mailer using your created Transport
    $mailer = Swift_Mailer::newInstance($transport);

    //Create a message
    $message = Swift_Message::newInstance('Test')
      ->setFrom(array('007@gmail.com' => 'From mr. 007'))
      ->setTo(array('007@gmail.com', '007@gmail.com' => 'To mr. 007'))
      ->setBody('Body')
      ;

    //Send the message
    $result = $mailer->send($message);

    /*
    You can alternatively use batchSend() to send the message

    $result = $mailer->batchSend($message);
    */ 
}

Here is the error:

( ! ) Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?) in C:\Program Files\wamp\www\swift-mailer\lib\classes\Swift\Transport\StreamBuffer.php on line 233

( ! ) Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP? #44551400]' in C:\Program Files\wamp\www\swift-mailer\lib\classes\Swift\Transport\StreamBuffer.php on line 235

( ! ) Swift_TransportException: Connection could not be established with host smtp.gmail.com [Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP? #44551400] in C:\Program Files\wamp\www\swift-mailer\lib\classes\Swift\Transport\StreamBuffer.php on line 235

Where is the problem??

Update:

I checked phpinfo() and it says:

OpenSSL support     disabled (install ext/openssl) 

I referred to the links below, but I couldn't install ssl...


Source: (StackOverflow)