Php mail sender id

Почтовая программа. Отправка почты на PHP

В двух предыдущих статьях мы настроили сервер и домен для дальнейшей отправки почты. Пришло время написать простую программу, которая и будет осуществлять рассылку. Поскольку реализуем мы все под веб-сервер, то писать скрипт будем на PHP.

Отправить письмо с сервера можно 3-я способами:

  • через функцию mail() — самый простой и менее надежный вариант, его рассматривать не будем, кого интересует данный вид отправки, можете почитать в документации PHP;
  • через SMTP-сервер, как собственный, так и сторонний — самый оптимальный вид отправки сообщений, его подробнее и рассмотрим в данной статье;
  • через сторонние сервисы, такие как Amazon, Mandrill, Mailgun и прочее — хорошее и простое решения, но зачастую использование подобных серверов, может оказаться дороже собственного сервера. Подробнее рассмотрим в другой статье.

Для отправки письма через SMTP-сервер необходимо:

  • данные для доступа к SMTP-серверу;
  • e-mail получателя;
  • письмо и его заголовок;
  • системные заголовки.

С электронным адресом получателя, текстом письма и его заголовком, проблем нету. Данные для доступа мы имеем, обычно это хост, порт и пара логин/пароль. Остается составить системные заголовки, в них то и кроется вся сложность исходной задачи.

Создание системных заголовков

Рассмотрим основной набор заголовков, которое должно иметь письмо претендующее на попадание в папку «Входящие»:

Date: D, d M Y H:i:s UTС Subject: =?utf-8?B?base64_encode(subject)=?= Reply-To: name MIME-Version: 1.0 Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 8bit From: name To: name Message-ID: Errors-To: email X-Complaints-To: email X-Sender: email List-Unsubscribe: List-id: Precedence: bulk
  • Date— дата отправки;
  • Subject— заголовок сообщения перекодированный в base64, чтобы избежать проблем с кодировкой;
  • Reply-To — имя и e-mail для ответа;
  • MIME-Version— версия MIME-стандарта;
  • Content-Type — тип письма и его кодировка, тип письма обычно указывается html либо plain (текстовая версия);
  • Content-Transfer-Encoding — тип конвертации, обычно используется «8bit»;
  • From— имя и e-mail отправителя;
  • To— имя и e-mail получателя;
  • Message-ID — id сообщения в вашей системе;
  • Errors-To — e-mail, куда будут отправлена информация о возникших ошибках;
  • X-Complaints-To — e-mail, куда будут отправлена информация о возникших жалобах;
  • X-Sender — e-mail системного отправителя;
  • List-Unsubscribe — здесь указывается ссылка или e-mail для отписки;
  • List-id — id текущей рассылки, для статистики;
  • Precedence— этот заголовок необходим в случае массовой рассылки, значение ставится bulk.

Класс для отправки почты на PHP

С необходимыми заголовками разобрались, переходим теперь к написанию класса, который будет осуществлять отправку почты.

class MailSender < /* данные для подкючения */ private $default = array( 'smtp_host' =>'127.0.0.1', 'smtp_port' => '25', 'smtp_login' => 'info@site.com', 'smtp_pass' => '1234567890', 'charset' => 'utf-8', 'from_name' => 'My name', 'from_email' => 'info@site.com', 'email_errors' => 'errors@site.com', ); /* функция отправки сообщений */ public static function send($email, $subject, $message, $unsub, $message_id = '', $list_id = '', $headers = '', $type = 'html') < $config = self::$default; /* проверка существования заголовков */ if(empty($headers)) < $headers = self::getHeaders($email, $subject, $type, $unsub, $message_id, $list_id); >/* добавление заголовков к сообщению */ $message = $headers . $message; /* создание сокета для подключения к SMTP-серверу */ if(!$socket = fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 30)) < echo $errno . "
" . $errstr; return false; > fputs($socket, "EHLO " . $config['smtp_host'] . "\r\n"); fputs($socket, "AUTH LOGIN\r\n"); fputs($socket, base64_encode($config['smtp_login']) . "\r\n"); fputs($socket, base64_encode($config['smtp_pass']) . "\r\n"); fputs($socket, "MAIL FROM: \r\n"); fputs($socket, "RCPT TO: \r\n"); fputs($socket, "DATA\r\n"); fputs($socket, $message . "\r\n.\r\n"); fputs($socket, "QUIT\r\n"); fclose($socket); return true; > /* функция генерации заголовков */ private static function getHeaders($email, $subject, $type, $unsub, $message_id, $list_id) < $config = self::$default; $result = ''; $result = "Date: ".date("D, d M Y H:i:s") . " UT\r\n"; $result .= "Subject: =?" . $config['charset'] . "?B?" . base64_encode($subject) . "=?=\r\n"; $result .= "Reply-To: " . $config['from_name'] . " \r\n"; $result .= "MIME-Version: 1.0\r\n"; $result .= "Content-Type: text/" . $type . "; charset=\"" . $config['charset'] . "\"\r\n"; $result .= "Content-Transfer-Encoding: 8bit\r\n"; $result .= "From: " . $config['from_name'] . " \r\n"; $result .= "To: " . $email['name'] . " \r\n"; $result .= "Errors-To: \r\n"; $result .= "X-Complaints-To: " . $config['email_errors'] . "\r\n"; $result .= "List-Unsubscribe: >\r\n"; if(!empty($list_id)) $result .= "List-id: \r\n"; $result .= "Precedence: bulk\r\n"; return $result; > >

Отправка пробного письма

Для рассылки, почти, все готово, остается проверить, отправив пробное письмо.

require_once 'MailSender.php'; $email = array( 'email' => 'demo@site.com', 'name' => 'Имя', ); $subject = 'Тестовое письмо'; $message = '

Это текст тестового письма.

'; $unsub = 'https://site.com/'; MailSender::send($email, $subject, $message, $unsub);

Скачать готовый скрипт можно здесь.

На этом с отправкой почты заканчиваем, если возникли вопросы, задаем их в комментариях.

Читайте также:  Python tkinter disable button

Источник

How to get mail message id from PHP before or after sending

What is the way in php to send emails from any email address? But the address from which the email will be sent will vary from time to time.

How to get mail message id from PHP before or after sending

I want to keep track of users who assign emails as spam, then remove them from the mailing list, or just put notification to 0 for them, so they don’t get emails anymore.

Mail feedback loops help you do that, but they return the message with the message id only, they do not tell you which email address it was from.

So I was wondering, how can I retrieve the message id from the mail which is sent with the PHP mail() function?

You can’t get the message ID for mail sent via the mail() command. That message ID is generated by sendmail, or whatever else is downstream.

You would need to use something else to generate your mail with, such as PHPMailer, or one of the many other alternatives.

Php — sending mail and sending in database, I have a form in which the data gets submitted to database but it doesn’t sends mail kindly help me send mail and database storing in both, the name of the PHP file is contactform.php after clicking the name of the PHP file is contactform.php after clicking submit button it should also go to thank you page …

PHP imap, send to message id?

I’m building a php application that can read, reply and send emails. I use php imap to retrieve the emails. Each email has a message-id that looks like 5981e1f444a81f1fc60549beb91ce060bc795d20@domain.co.uk . I attempted to reply to this specific message with my php application but not working. I’m using test@domain.co.uk as mail server, i retrieve emails to my php application with php imap. Each email has a message-id, how do i reply to a specific message? How do i solve?; the below example doesn’t work.

/* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to email: ' . imap_last_error()); /* grab emails */ $emails = imap_search($inbox,'ALL'); /* if emails are returned, cycle through each. */ if($emails) < /* begin output var */ $output = ''; /* put the newest emails on top */ rsort($emails); /* for every email. */ foreach($emails as $email_number) < /* get information specific to this email */ $overview = imap_fetch_overview($inbox,$email_number,0); $message = imap_fetchbody($inbox,$email_number,2); $headers = "From: test@plantsandtreesonline.co.uk \r\n"; $headers .= "Reply-To: ".$overview[0]->message_id."\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $subject = "testing"; $message = "test message2"; wp_mail( $overview[0]->message_id, $subject, $message, $headers ); > echo $output; > /* close the connection */ imap_close($inbox); 

I think you want «In-Reply-To:» instead of «Reply-To:» for the header with the message id. «Reply-To» would be an email address — who the reply should be sent to.

Читайте также:  How to print new lines in python

How to send an email using PHPMailer, 1: Display output messages sent by the client. 2: As 1, plus display responses received from the server. 3: As 2, plus more information about the initial connection – this level can help diagnose STARTTLS failures. 4: As 3, plus display even lower-level information. isSMTP(): Set mailer to use SMTP. isMail(): Set …

Php, send email from any email address

Email will be delivered to people — a veryusual thing.

But the address from which the email will be sent will vary from time to time. And the address from which the mail will be sent will be taken as an input from the site admin.

The thing is, to send email from a gmail account needs a certain type of coding, to do it with yahoo needs another kind of coding and so on.

What is the way in php to send emails from any email address?

Is there any such script available for free ?

The correct way of sending email is through a SMTP connection. Assuming the PEAR Mail package is installed.

"; $to = "Name Whatever "; $subject = "Subject!"; $body = "Hi,\n\nHow are you?"; $host = "mail.yourdomain.com"; $username = "smtp_username"; $password = "smtp_password"; $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); $smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) < echo("

" . $mail->getMessage() . "

"); > else < echo("

Message successfully sent!

"); > ?>

Assuming you have Zend Framework, you can do the same by sending through zend_mail over SMTP. The example below uses information on Google SMTP

require_once 'Zend/Loader/Autoloader.php'; //Should be in the include_path $autoloader = Zend_Loader_Autoloader::getInstance(); $config = array('ssl' => 'tls', 'port' => 587, 'auth' => 'login', 'username' => 'username@gmail.com', 'password' => 'password'); $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config); $mail = new Zend_Mail(); if (strtolower($this->getType()) == 'html') $mail->setBodyHtml($this->getBody()); > else < $mail->setBodyText($this->getBody()); > $mail ->setFrom($this->getFromEmail(), $this->getFromName()) ->addTo($this->getToEmail(), $this->getToName()) ->setSubject($this->getSubject()); $mail->send($transport); 

Basically, you set your mail headers which are containing, who is sending that email address. Fortunately, this mostly will arrive as spam (keywords: SPF, DNS PTR, . )

Читайте также:  Стили

Easiest thing would be to create classes for every account you are going to use (gmail, yahoo, . ) and then use the factory pattern to keep your code clean.

Best option would be: Use smtp with authentication. This is the most supported standard and you only have to code solutions for services that don’t provide smtp auth.

I don’t know how to help you. You want to send mails from every domain, without them being flagged as spam, just by providing a «mail from (enter email address here)» input field, and a full-magic-do-it-everything-script-package. But without having an idea of how mailing works.

Pro tip: read about SMTP and get an idea of how sending mails is working.

Sending an email with php plain text and html, In order to create a multipart/alternative message, you need to specify a boundary and separate each part by that boundary. A good boundary string would be something that is highly unlikely to occur in the message part itself, such as a random string generated by sha1(uniqid()).For example:

PHP send email message coding in utf-8 [duplicate]

I have a problem with sending mail from php code. I want to use polish characters in email message. I searched many post on stack with the same problem but nothing works.

I have asked my friend to check on his vps and this code work correctly. So there must be a problem with server. I use linuxpl.com.

I found the solution. Polish characters work fine when I added this line in html form.

mail($to,utf8_decode($subject),utf8_decode($message),utf8_decode($headers)); 

Sending Email with content from PHP/Mysql, I want to send emails where the data is from a php/mySQL query. I know that html will render in the email but i don’t think the php codes will. It makes it very easy to generate multi-part messages (plaintext + html, with attachments and embedded/inline images). Basically:

Источник

Оцените статью