Question

I want to send custom email programmatically without any template.

In magento 1, I used below script to do same thing.

$mail = Mage::getModel('core/email');
$mail->setToName('xxx');
$mail->settoemail('xxx@yyy.com');
$mail->setBody($html);
$mail->setSubject('Test email : '.$fieldss['o']);
$mail->setfromemail('from@yopmail.com');
$mail->setType('html');// YOu can use Html or text as Mail format
$mail->setBodyHTML($html);  // your content or message
try{ 
    $mail->send();
}catch (Exception $e) {
    echo $e->getMessage();exit;
}

Here, In magento 2 I used below code but it gives error.

$objectManager = $this->getObjectManager();
$transport = $objectManager->get('Magento\Framework\Mail\Template\TransportBuilder');
$transport->addTo('xxx@yyy.com', 'Hiren Shah');
//$transport->settoemail('hiren.shah@healthtrader.com');
//$transport->setBody($html);
$transport->setSubject('Test email : '.$fieldss['o']);
$transport->setFrom('from@yopmail.com');
$transport->setType('html');// YOu can use Html or text as Mail format
$transport->setBodyHTML($html);  // your content or message
$transport->getTransport();
try { 
    $transport->sendMessage();
} catch (Exception $e) {
    echo $e->getMessage();exit;
}

But this gives me error Call to undefined method Magento\Framework\Mail\Template\TransportBuilder\Interceptor::setSubject()

How to send custom email without template? Please give me code sample.

Was it helpful?

Solution

Magento 2: The simplest way I found to send a plain text - use Zend1 mail

    $to = ['email1@test.com', 'email2@test.com'];
    $email = new \Zend_Mail();
    $email->setSubject("Feedback email");
    $email->setBodyText($body);
    $email->setFrom($from, $nameFrom);
    $email->addTo($to, $nameTo);
    $email->send();

OTHER TIPS

You can send mail using Zend_Mail() function.

$firstname = "xxx";
$lastname = "yyyyyy";

// Send Mail functionality starts from here 
$from = "from_address@example.com";
$nameFrom = "From Name";
$to = "to_address@example.com";
$nameTo = "To Name";
$body = "
<div>
    <b>".$firstname."</b>
    <i>".$lastname."</i>
</div>";

$email = new \Zend_Mail();
$email->setSubject("Email Subject"); 
$email->setBodyHtml($body);     // use it to send html data
//$email->setBodyText($body);   // use it to send simple text data
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top