【问题标题】:swift Mailer - set To with PHP variablesswift Mailer - 使用 PHP 变量设置为
【发布时间】:2013-07-18 20:58:25
【问题描述】:

只是看看使用 Swift Mailer 从 Windows 服务器发送电子邮件。我有一个带有输入字段的简短表单,允许网络用户添加他们的电子邮件地址(id 是email),我需要能够将email PHP 变量注入setTo SwiftMailer 代码以允许要发送到指定电子邮件地址的邮件...有人知道怎么做吗?

基本代码是

// Set the To addresses with an associative array
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))

我需要让它使用$email 而不是receiver@domain.org

有什么想法吗?

【问题讨论】:

  • 如果您允许客户端注入电子邮件的发送位置,请务必小心。垃圾邮件发送者可能会将您的服务器列入黑名单。

标签: php email swiftmailer


【解决方案1】:

您需要捕获发布的值。

// Set the To addresses with an associative array
$email = $_POST['email'];
->setTo(array($email));

假设您的 HTML 类似于

<form method="post">
    Email: 
    <input type="text" name="email" id="email_id" />
</form>

请记住,name input 属性是您希望用 PHP 捕获的。 id 不会传递给您的 PHP 脚本。

PHP Documentation - Dealing with Forms

Swiftmail Creating Messages Documentation

【讨论】:

    【解决方案2】:

    您的意思是您有一个POSTGET 输出用户在“电子邮件”字段中输入的电子邮件地址(例如:name="email")?试试这个:

    $mailer->setTo($_POST['email']);
    

    有趣的是,您可以将它与name="email[]" 一起使用,您可以再次简单地将$_POST['email'] 传递给setTo,然后就完成了! :)

    $mailer->setTo(array(
        'email-1@domain.tld' => 'Name 1',
        'email-2@domain.tld' => 'Name 2',
        'email-3@domain.tld' => 'Name 3',
        'email-4@domain.tld' => 'Name 4',
    ));
    

    您还可以使用更多示例,例如将name="email[]"name="name[]" 结合起来,如下所示:

    $mailer->setTo(array_combine($_POST['email'], $_POST['name']));
    

    请注意,要使 array_combine 工作,您需要两个长度相同的数组。像这样保护您的代码(可以扩展以满足您的需求):

    $emails =& $_POST['emails'];
    $names =& $_POST['name'];
    
    if (count($emails) > count($names)) {
        $emails = array_slice($emails, 0, count($names));
    } 
    
    else if (count($names) > count($emails)) {
        $names = array_slice($names, 0, count($emails));
    }
    
    $mailer->setTo(array_combine($emails, $names));
    

    祝你好运!

    【讨论】:

      【解决方案3】:

      谢谢大家 - 这个方法奏效了:

      ->setTo($email)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-12
        • 2011-10-05
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 2011-08-22
        • 2012-11-19
        • 2013-02-07
        相关资源
        最近更新 更多