phpMailer doesn't send emails to hotmail account - php

I'm using PHPMailer to send emails. I'm trying to send an email to an Hotmail account but if the recipient has the sender in contacts, it receives the email. If the recipient doesn't have the sender in contacts, it doesn't receive the email.
Why? What is the matter?
PHPMailer doesn't show any errors.
I have tried a lot of solutions proposed in the network without any result.
This is the code that I use:
public static function invia_email_bis($p_nome_mitt, $p_mitt, $p_dest, $p_ccn, $p_oggetto, $p_header, $p_mess) {
//Se siamo in sviluppo, le email non devono partire. L'ambiente lo rileviamo dal DB
$config =& JFactory::getConfig();
if ($config->getValue( 'config.db' ) == 'fantaonl_dev') {
return;
}
$email_par = email::get_parameter(costanti::actaccount);
//Creazione dell'oggetto PHPMAILER
$messaggio = new PHPmailer();
//Abilitiamo SMTP
$messaggio->IsSMTP();
//Abilitiamo l'autenticazione
$messaggio->SMTPAuth = true;
//Abilitiamo il protocollo SSL
if ( $email_par['PORTA'] == 587 ) {
$messaggio->SMTPSecure = "tls";
}
if ( $email_par['PORTA'] == 465 ) {
$messaggio->SMTPSecure = "ssl";
}
//Server SMTP
$messaggio->Host = $email_par['SMTP'];
$messaggio->Username = $email_par['USERNAME'];
$messaggio->Password = $email_par['PASSWORD'];
//Porta
$messaggio->Port = $email_par['PORTA'];
//Definiamo le intestazioni e il corpo del messaggio
$messaggio->FromName = $p_nome_mitt;
$messaggio->From = $p_mitt;
//$messaggio->SMTPDebug = 1;
//$messaggio->Debugoutput = 'html';
//DESTINATARIO
if ($p_ccn == false) {
for ($t = 0; $t < count($p_dest); $t++) {
if ($p_dest[$t]['EMAIL'] != '') { $messaggio->AddAddress($p_dest[$t]['EMAIL']); }
elseif ($p_dest[$t]['email'] != '') { $messaggio->AddAddress($p_dest[$t]['email']); }
}
}
else {
for ($t = 0; $t < count($p_dest); $t++) {
if ($p_dest[$t]['EMAIL'] != '') { $messaggio->AddBCC($p_dest[$t]['EMAIL']); }
elseif ($p_dest[$t]['email'] != '') { $messaggio->AddBCC($p_dest[$t]['email']); }
}
}
//DESTINATARIO IN CCN
//$mail->AddBCC($p_dest);
//MITTENTE
$messaggio->AddReplyTo($p_mitt, $p_nome_mitt);
//OGGETTO MESSAGGIO
$messaggio->Subject=$p_oggetto;
//Il Messaggio Ë in HTML
$messaggio->IsHTML(true);
$path_html = $_SERVER['DOCUMENT_ROOT'] . '/jumi_includes/class/template_email.html';
$message_body = file_get_contents($path_html);
$message_body = str_replace('%titolo%', $p_header, $message_body);
$message_body = str_replace('%messaggio%', $p_mess, $message_body);
$path_img = $_SERVER['DOCUMENT_ROOT'] . '/templates/sitodefinitivodue/images/header.jpg';
//Path immagine da caricare
$messaggio->AddEmbeddedImage($path_img, 'header', 'header.jpg', 'base64', 'image/jpeg');
//CORPO MESSAGGIO
$messaggio->MsgHTML($message_body);
$messaggio->AltBody = $p_mess;
//Definiamo i comportamenti in caso di invio corretto
//o di errore
if(!$messaggio->Send()){
$esito = 4;
//echo $messaggio->ErrorInfo;
}else{
$esito = 0;
}
//chiudiamo la connessione
$messaggio->SmtpClose();
unset($messaggio);
return $esito;
}

It's hotmails spamfilter who kicks in. Nowdays you can't just starting send e-mails and think it will get all the way.
To dodge hotmails/gmails spam filter you must:
Oblige to USA's CAN-SPAM Act of 2003 witch includes:
Never use deceptive headers, from-names, reply-tos, or subject lines.
You must always provide an unsubscribe link.
Remove recipients from your list within 10 business days.
The unsubscribe link must work for at least 30 days after sending.
You must include your physical mailing address. To learn more, go to ftc.gov.
Send from the correct server, if the SMTP-server you are using dosn't have anything with the domain name you are using it will be blocked. If you send a no-reply#test.com and don't use the correct smtp it will be blocked, and if you continue your smtp server can be blacklisted and if you use an ISP or any other server they will not be happy about it.
Not be "spam", spamfilter nowdays analyses the text and tries to figure out if your mail is spam. If you send alot of the same massage with just small text changes your mail will score higher. Like: Hello [Mike], look at our new products etc etc. Avoid using common spam words like e CLICK HERE! or FREE! BUY NOW! etc or bright colors, lots of exclamation, vad html etc.
There is no bulletproff way to avoid a spam filter, if it would your inbox would be filled with spam in no time.
Will Weatons rule apply here (as with SEO): Don't be a dick.

I think your email has been sent to hotmail user.
To send correctly to hotmail, be sure to be correct with DKIM.
I doubt it would be DKIM issue.
In Hotmail's Safe Sender will auto ignore the email if the sender domain not in the safe list.
Try to check:-
Inbox > Options > Safe and blocked senders > Safe senders

Related

gmail api strait forward way to get sender email

I’m having problems getting the sender's email address,
$single_message = $gmail->users_messages->get('me', $msg_id);
"from" usually yields the senders name
To get the email address I have this code
if($partes->getName() == 'Authentication-Results')
{
$outh_res = $partes->getValue();
if(strpos($outh_res, 'smtp.mailfrom=') !== false)
{
$bits = explode('smtp.mailfrom=',$outh_res);
$mail = $bits[1];
if(strpos($mail, ';') !== false)
{
$bits = explode(';',$mail);
$mail = str_replace('"', '',$bits[0]);
}
}
}
That always gives me an email, but when the sender is behind mail chimp (or their own servers (postfix)) for example: bounces+2063633-785c-info=myemail.com#sg1.senderemail.com
In the best case I receive #sendermail.com (from gmail itself I know its info#sendermail.com) so it's useless
In some cases
if($partes->getName() == 'Reply-To')
{
$other_mail = str_replace('"', '',$partes->getValue());
}
Gives me a helpful email others just the senders name
as suggested in github php gmail api issue # 521 and other places
$only_header = $gmail->users_messages->get('me',$msg_id, ['format' => 'metadata', 'metadataHeaders' => ['To','X-Original-To','X-Original-From','From','Reply-To','Subject']]);
It gives exactly the same info.
Is there any way that the api gives me exactly the sender email address even if it's behind mail chimp or other 3rd party sender?
There's a similar answer Get sender email from gmail-api, I already loop the headers and tried zingzinco's answer.
Edit: Thanks to Joey Tawadrous;
Php code:
if($partes->getName() == 'From')
{
$raw_from = $partes->getValue();
if(strpos($raw_from, '<') !== false)
{
$bit = explode('<',$raw_from);
$bit2 = explode('>',$bit[1]);
$final_email = $bit2[0];
$sender_name = str_replace('"', '',$bit[0]);
}
else
{
$sender_name = limpiarm(str_replace('"', '',$raw_from));
}
}
var email = '';
var messageFrom = _.where(message.payload.headers, {name: 'From'})[0].value;
if(messageFrom.includes('<')) {
var fromObj = messageFrom.split('<');
email = fromObj[1];
fromObj = email.split('>');
email = fromObj[0];
}
return email;

PHP - Verifying emails existance [duplicate]

I have a question, i have a php script to check if the email address exist.
But appear that yahoo, hotmail, aol and others providers are accepting any emails and not rejecting the invalid emails.
Only Gmail, and many domains like stackoverflow.com are rejecting the no vaild emails.
Check my script and let me know if i can do some to check the yahoo and others.
html post form
<html>
<body>
<form action="checkemail.php" method="POST">
<b>E-mail</b> <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
php
<?php
/* Validate an email address. */
function jValidateEmailUsingSMTP($sToEmail, $sFromDomain = "gmail.com", $sFromEmail = "email#gmail.com", $bIsDebug = false) {
$bIsValid = true; // assume the address is valid by default..
$aEmailParts = explode("#", $sToEmail); // extract the user/domain..
getmxrr($aEmailParts[1], $aMatches); // get the mx records..
if (sizeof($aMatches) == 0) {
return false; // no mx records..
}
foreach ($aMatches as $oValue) {
if ($bIsValid && !isset($sResponseCode)) {
// open the connection..
$oConnection = #fsockopen($oValue, 25, $errno, $errstr, 30);
$oResponse = #fgets($oConnection);
if (!$oConnection) {
$aConnectionLog['Connection'] = "ERROR";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = false; // unable to connect..
} else {
$aConnectionLog['Connection'] = "SUCCESS";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = true; // so far so good..
}
if (!$bIsValid) {
if ($bIsDebug) print_r($aConnectionLog);
return false;
}
// say hello to the server..
fputs($oConnection, "HELO $sFromDomain\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['HELO'] = $oResponse;
// send the email from..
fputs($oConnection, "MAIL FROM: <$sFromEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailFromResponse'] = $oResponse;
// send the email to..
fputs($oConnection, "RCPT TO: <$sToEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailToResponse'] = $oResponse;
// get the response code..
$sResponseCode = substr($aConnectionLog['MailToResponse'], 0, 3);
$sBaseResponseCode = substr($sResponseCode, 0, 1);
// say goodbye..
fputs($oConnection,"QUIT\r\n");
$oResponse = fgets($oConnection);
// get the quit code and response..
$aConnectionLog['QuitResponse'] = $oResponse;
$aConnectionLog['QuitCode'] = substr($oResponse, 0, 3);
if ($sBaseResponseCode == "5") {
$bIsValid = false; // the address is not valid..
}
// close the connection..
#fclose($oConnection);
}
}
if ($bIsDebug) {
print_r($aConnectionLog); // output debug info..
}
return $bIsValid;
}
$email = $_POST['email'];
$bIsEmailValid = jValidateEmailUsingSMTP("$email", "gmail.com", "email#gmail.com");
echo $bIsEmailValid ? "<b>Valid!</b>" : "Invalid! :(";
?>
If you need to make super sure that an E-Mail address exists, send an E-Mail to it. It should contain a link with a random ID. Only when that link is clicked, and contains the correct random ID, the user's account is activated (or ad published, or order sent, or whatever it is that you are doing).
This is the only reliable way to verify the existence of an E-Mail address, and to make sure that the person filling in the form has access to it.
There is no 100% reliable way of checking the validity of an email address. There are a few things you can do to at least weed out obviously invalid addresses, though.
The problems that arise with email addresses is actually very similar to those of snail mail. All three points below can also be used for sending snail mail (just change the DNS record with a physical address).
1. Check that the address is formatted correctly
It is very difficult to check the format of email addresses, but PHP has a validation filter that attempts to do it. The filter does not handle "comments and folding whitespace", but I doubt anyone will notice.
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE) {
echo 'Valid email address formatting!';
}
2. Check that the DNS record exists for the domain name
If a DNS (Domain Name System) record exists then at least someone has set it up. It does not mean that there is an email server at the address, but if the address exists then it is more likely.
$domain = substr($email, strpos($email, '#') + 1);
if (checkdnsrr($domain) !== FALSE) {
echo 'Domain is valid!';
}
3. Send a verification email to the address
This is the most effective way of seeing if someone is at the other end of the email address. If a confirmation email is not responded to in an orderly fashion -- 3 hours for example -- then there is probably some problem with the address.
You can validate "used or real" emails with Telnet and MX records more info in here, for PHP exists a great library call php-smtp-email-validation that simplify the process.
You create a boolean function with the file example1.php and call it when you'll validate the email text. For Gmail, Hotmail, Outlook, live and MSM I don's have any problems but with Yahoo and Terra the library can't validate correctly emails
The problem is gmail uses port 25 for their smtp outgoing mails, the other providers use different ports for their connection. Your response seems okay for gmail.com.
When you connect to gmail smtp it gives you response 250 2.1.5 OK j5si2542844pbs.271 - gsmtp
But when you connect to any other smtp who does not use port 25 it gives you null response.

How to change a pipe-forwarded email's "From" and "To" section in PHP

I am trying to mask emails. Basically give an email to a client like "RandomName#MyDomain.com" and have it forward "MyRealEmail#MyDomain.com".
I am pipe forwarding the emails to a php script on my server, where I want to use the "To" and "From" to find the real recipient of the message and forward the message to them removing any identifiable information from the Sender (From) section.
I can parse almost all the data right now from the header, but my problem is with the body. The html body portion can vary so much from different origins. Outlook have a <html> and <body> section, while Gmail just has <div>s. Regardless, I get these strange "=" signs in my raw email too, in both text and html sections, like <=div>!
I just want to change the "From" and "To" and keep the rest of the email pretty much exactly as it is so it doesn't have anomalies in its text or html section.
How can I do this? Should I just parse the raw email and change the occurrences of the emails? how can I send it then? or should I remake the email using phpmailer or some other class? how can i get the body correct then?
My hosting provider doesn't have MailParse extension installed, since I have seen some solutions on the site using that extension, so I am having to do this using available extensions in PHP 5.5
UPDATE
I managed to figure out the = issue, it was quoted-printable, so now I am calling quoted_printable_decode() to resolve that issue. Still trying to figure the best way to forward the email after altering the header though.
After a lot of failed attempts, finally have a solution I can live with. The host server didn't want to allow MailParse because it was an issue on their shared hosting environment, so I went with Mail_mimeDecode and Mail_MIME PEAR extensions.
// Read the message from STDIN
$fd = fopen("php://stdin", "r");
$input = "";
while (!feof($fd)) {
$input .= fread($fd, 1024);
}
fclose($fd);
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$decoder = new Mail_mimeDecode($input);
$structure = $decoder->decode($params);
// get the header From and To email
$From = ExtractEmailAddress($structure->headers['from'])[0];
$To = ExtractEmailAddress($structure->headers['to'])[0];
$Subject = $structure->headers['subject'];
ExtractEmailAddress uses a solution from "In PHP, how do I extract multiple e-mail addresses from a block of text and put them into an array?"
For the Body I used the following to find the text and html portions:
$HTML = "";
$TEXT = "";
// extract email body details
foreach($structure as $K => $V){
if(is_array($V)){
foreach($V as $KK => $VV){
if(is_object($VV)){
$bodyHTML = false;
$bodyPLAIN = false;
foreach($VV as $KKK => $VVV){
if(!is_array($VVV)){
if($KKK === 'ctype_secondary'){
if($VVV === 'html') { $bodyHTML = true; }
if($VVV === 'plain') { $bodyPLAIN = true; }
}
if($KKK === 'body'){
if($bodyHTML){
$bodyHTML = false;
$HTML .= quoted_printable_decode($VVV);
}
if($bodyPLAIN){
$bodyPLAIN = false;
$TEXT .= quoted_printable_decode($VVV);
}
}
}
}
}
}
}
}
Finally, I had the parts I needed so I used Mail_MIME to get the message out. I do my database lookup logic here and find the real destination and masked From email address using the From and To I extracted from the header.
$mime = new Mail_mime(array('eol' => "\r\n"));
$mime->setTXTBody($TEXT);
$mime->setHTMLBody($HTML);
$mail = &Mail::factory('mail');
$hdrs = array(
'From' => $From,
'Subject' => $Subject
);
$mail->send($To, $mime->headers($hdrs), $mime->get());
I don't know if this will cover all cases of email bodies, but since my system is not using attachments I am ok for now.
Take not of quoted_printable_decode(), that how I fixed the issue with the = in the body.
The only issue is the delay in mail I am having now, but I'll deal with that

Can not send email threw SwiftMailer with Mandrill

Since today, many of my php applications can not send email using SwiftMailer and different Mandrill accounts.
I've got this code, and the send function in the last if stop the script..
// Instance message
$message = Swift_Message::newInstance();
$message->setSubject("subject")
->setFrom(array('noreply#email.test' => 'test'))
->setTo(array('a_valid_email' => 'name'))
->setBody("test", 'text/html')
->setPriority(2);
$smtp_host = 'smtp.mandrillapp.com';
$smtp_port = 587;
$smtp_username = 'valid_username';
$smtp_password = 'valid_password';
// SMTP
$smtp_param = Swift_SmtpTransport::newInstance($smtp_host , $smtp_port)
->setUsername($smtp_username)
->setPassword($smtp_password);
// Instance Swiftmailer
$instance_swiftmailer = Swift_Mailer::newInstance($smtp_param);
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'iso-8859-1');
//Here the send function stop event and I did not go inside the if
if ($instance_swiftmailer->send($message, $fail)) {
echo 'OK ';
}else{
echo 'NOT OK : ';
print_r($fail);
}
Thank you in advance to help me to solve this problem..
If your code used to work, and now doesn't work, and you didn't change your code, then it's probably not a problem with your code. Check your Mandrill account validity - sometimes they suspend accounts for suspicious-appearing usage.

How to Validate email address exist or not in php? [duplicate]

I have a question, i have a php script to check if the email address exist.
But appear that yahoo, hotmail, aol and others providers are accepting any emails and not rejecting the invalid emails.
Only Gmail, and many domains like stackoverflow.com are rejecting the no vaild emails.
Check my script and let me know if i can do some to check the yahoo and others.
html post form
<html>
<body>
<form action="checkemail.php" method="POST">
<b>E-mail</b> <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
php
<?php
/* Validate an email address. */
function jValidateEmailUsingSMTP($sToEmail, $sFromDomain = "gmail.com", $sFromEmail = "email#gmail.com", $bIsDebug = false) {
$bIsValid = true; // assume the address is valid by default..
$aEmailParts = explode("#", $sToEmail); // extract the user/domain..
getmxrr($aEmailParts[1], $aMatches); // get the mx records..
if (sizeof($aMatches) == 0) {
return false; // no mx records..
}
foreach ($aMatches as $oValue) {
if ($bIsValid && !isset($sResponseCode)) {
// open the connection..
$oConnection = #fsockopen($oValue, 25, $errno, $errstr, 30);
$oResponse = #fgets($oConnection);
if (!$oConnection) {
$aConnectionLog['Connection'] = "ERROR";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = false; // unable to connect..
} else {
$aConnectionLog['Connection'] = "SUCCESS";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = true; // so far so good..
}
if (!$bIsValid) {
if ($bIsDebug) print_r($aConnectionLog);
return false;
}
// say hello to the server..
fputs($oConnection, "HELO $sFromDomain\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['HELO'] = $oResponse;
// send the email from..
fputs($oConnection, "MAIL FROM: <$sFromEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailFromResponse'] = $oResponse;
// send the email to..
fputs($oConnection, "RCPT TO: <$sToEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailToResponse'] = $oResponse;
// get the response code..
$sResponseCode = substr($aConnectionLog['MailToResponse'], 0, 3);
$sBaseResponseCode = substr($sResponseCode, 0, 1);
// say goodbye..
fputs($oConnection,"QUIT\r\n");
$oResponse = fgets($oConnection);
// get the quit code and response..
$aConnectionLog['QuitResponse'] = $oResponse;
$aConnectionLog['QuitCode'] = substr($oResponse, 0, 3);
if ($sBaseResponseCode == "5") {
$bIsValid = false; // the address is not valid..
}
// close the connection..
#fclose($oConnection);
}
}
if ($bIsDebug) {
print_r($aConnectionLog); // output debug info..
}
return $bIsValid;
}
$email = $_POST['email'];
$bIsEmailValid = jValidateEmailUsingSMTP("$email", "gmail.com", "email#gmail.com");
echo $bIsEmailValid ? "<b>Valid!</b>" : "Invalid! :(";
?>
If you need to make super sure that an E-Mail address exists, send an E-Mail to it. It should contain a link with a random ID. Only when that link is clicked, and contains the correct random ID, the user's account is activated (or ad published, or order sent, or whatever it is that you are doing).
This is the only reliable way to verify the existence of an E-Mail address, and to make sure that the person filling in the form has access to it.
There is no 100% reliable way of checking the validity of an email address. There are a few things you can do to at least weed out obviously invalid addresses, though.
The problems that arise with email addresses is actually very similar to those of snail mail. All three points below can also be used for sending snail mail (just change the DNS record with a physical address).
1. Check that the address is formatted correctly
It is very difficult to check the format of email addresses, but PHP has a validation filter that attempts to do it. The filter does not handle "comments and folding whitespace", but I doubt anyone will notice.
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE) {
echo 'Valid email address formatting!';
}
2. Check that the DNS record exists for the domain name
If a DNS (Domain Name System) record exists then at least someone has set it up. It does not mean that there is an email server at the address, but if the address exists then it is more likely.
$domain = substr($email, strpos($email, '#') + 1);
if (checkdnsrr($domain) !== FALSE) {
echo 'Domain is valid!';
}
3. Send a verification email to the address
This is the most effective way of seeing if someone is at the other end of the email address. If a confirmation email is not responded to in an orderly fashion -- 3 hours for example -- then there is probably some problem with the address.
You can validate "used or real" emails with Telnet and MX records more info in here, for PHP exists a great library call php-smtp-email-validation that simplify the process.
You create a boolean function with the file example1.php and call it when you'll validate the email text. For Gmail, Hotmail, Outlook, live and MSM I don's have any problems but with Yahoo and Terra the library can't validate correctly emails
The problem is gmail uses port 25 for their smtp outgoing mails, the other providers use different ports for their connection. Your response seems okay for gmail.com.
When you connect to gmail smtp it gives you response 250 2.1.5 OK j5si2542844pbs.271 - gsmtp
But when you connect to any other smtp who does not use port 25 it gives you null response.

Categories