2013-05-10 1 views
4

Я использую Gmail для отправки почты, так что я конфиг 'config.yml' как этотконфигурация SwiftMailer для более чем одного счета в Symfony 2

swiftmailer: 
transport: %mailer_transport% 
encryption: %mailer_encryption% 
auth_mode: %mailer_auth% 
host:  %mailer_host% 
username: %mailer_user% 
password: %mailer_password% 

'parameters.yml' как этот

mailer_transport: smtp 
mailer_encryption: ssl 
mailer_auth:  login 
mailer_host:  smtp.gmail.com 
mailer_user:  [email protected] 
mailer_password: ****** 

Теперь я хочу использовать больше почтовых учетных записей для отправки писем для разных целей. например: используйте [email protected] для отправки писем для приветствия; используйте [email protected] отправьте письма для сброса пароля.

Что я должен конфиг SwiftMailer?

ответ

1

В SwiftmailerBundle, которая управляет конфигурации почтовой программы, позволяет настроить только один конфигурации по умолчанию. Однако довольно просто настроить других. Просто используйте Swiftmailer напрямую или определите собственные классы почтовой программы с другими конфигурациями.

/** 
* Gets the 'mailer' service. 
* 
* This service is shared. 
* This method always returns the same instance of the service. 
* 
* @return Swift_Mailer A Swift_Mailer instance. 
*/ 
protected function getMailerService() 
{ 
    return $this->services['mailer'] = new \Swift_Mailer($this->get('swiftmailer.transport')); 
} 

Вы можете определить столько сервисов, сколько хотите, с другой конфигурацией. Например, посмотрите следующий пример.

<service id="mysecond.transport.smtp" class="%swiftmailer.transport.smtp.class%" public="false"> 
    <argument type="service" id="swiftmailer.transport.buffer" /> 
    <argument type="collection"> 
     <argument type="service" id="swiftmailer.transport.authhandler" /> 
    </argument> 
    <argument type="service" id="swiftmailer.transport.eventdispatcher" /> 

    <call method="setHost"><argument>%mysecond.transport.smtp.host%</argument></call> 
    <call method="setPort"><argument>%mysecond.transport.smtp.port%</argument></call> 
    <call method="setEncryption"><argument>%mysecond.transport.smtp.encryption%</argument></call> 
    <call method="setUsername"><argument>%mysecond.transport.smtp.username%</argument></call> 
    <call method="setPassword"><argument>%mysecond.transport.smtp.password%</argument></call> 
    <call method="setAuthMode"><argument>%mysecond.transport.smtp.auth_mode%</argument></call> 
    <call method="setTimeout"><argument>%mysecond.transport.smtp.timeout%</argument></call> 
    <call method="setSourceIp"><argument>%mysecond.transport.smtp.source_ip%</argument></call> 
</service> 

Тогда в вашем коде вы бы сделали что-то вроде.

$mySecondMailer = new \Swift_Mailer($this->get('mysecond.transport.smtp')); 

Это должно сделать трюк.

20

Если вы используете SwiftMailer 2.3.3 у вас есть возможность сделать все просто:

в parameters.yml оных:

mailer2_transport: smtp 
mailer2_encryption: ssl 
mailer2_auth_mode: login 
mailer2_host: smtp.gmail.com 
mailer2_user: [email protected] 
mailer2_password: ******* 

В config.yml вносить изменения:

swiftmailer: 
    default_mailer: mailer 
    mailers: 
     mailer: 
      transport: %mailer_transport% 
      host:  %mailer_host% 
      username: %mailer_user% 
      password: %mailer_password% 
      encryption: %mailer_encryption% 
      auth_mode: %mailer_auth_mode% 
     mailer2: 
      transport: %mailer2_transport% 
      host:  %mailer2_host% 
      username: %mailer2_user% 
      password: %mailer2_password% 
      encryption: %mailer2_encryption% 
      auth_mode: %mailer2_auth_mode% 

В коде, если вы пишете:

$mailer = $this->get('swiftmailer.mailer.mailer2'); 

вы получите настройки из своего раздела;

И если вы пишете:

$mailer = $this->get('swiftmailer.mailer.default'); 

или

$mailer = $this->get('mailer'); // default configuration 

вы будете использовать настройки из раздела по умолчанию;

+0

Пожалуйста не то, что обработчик auth делится. Если вы используете две почтовые программы с этой настройкой, с разными именами/паролями это не сработает. См. Https://github.com/symfony/SwiftmailerBundle/pull/70 и https://github.com/symfony/SwiftmailerBundle/issues/73 – rolandow

+3

Просто хочу указать, что у вас должна быть почтовая программа по умолчанию ' default ', иначе для вас будет создана почтовая программа для по умолчанию' default ', и вместо этого она будет использоваться по умолчанию. Я считаю, что это ошибка. – DavidLin

+0

Проблема с обработчиком авторизации, идентифицированная rolandow, была исправлена ​​в Swiftmailer. – Acyra

1

Как будет выглядеть ваш конфигурационный файл.

app/config/config.YML

swiftmailer: 
    default_mailer: second_mailer 
    mailers: 
     first_mailer: 
      # ... 
     second_mailer: 
      # ... 

Теперь вы можете использовать любого из почтовой программы в следующем способе:

// returns the first mailer 
$container->get('swiftmailer.mailer.first_mailer'); 

// also returns the second mailer since it is the default mailer 
$container->get('swiftmailer.mailer'); 

// returns the second mailer 
$container->get('swiftmailer.mailer.second_mailer'); 

Для получения более подробной информации см: symfony documentry

0

это должно работать: from the documentation

require_once 'lib/swift_required.php'; 

// Create the Transport 
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25) 
    ->setUsername('your username') 
    ->setPassword('your password') 
    ; 

/* 
You could alternatively use a different transport such as Sendmail or Mail: 

// Sendmail 
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); 

// Mail 
$transport = Swift_MailTransport::newInstance(); 
*/ 

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

// Create a message 
$message = Swift_Message::newInstance('Wonderful Subject') 
    ->setFrom(array('[email protected]' => 'John Doe')) 
    ->setTo(array('[email protected]', '[email protected]' => 'A name')) 
    ->setBody('Here is the message itself') 
    ; 

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

 Смежные вопросы

  • Нет связанных вопросов^_^