I've been searching for days if not weeks on how to automatically send a simple e-mail in php after a user completes my form. I've tried Pear, PHP mail, Swiftmailer, changed my php.ini, tried different servers and I'm going mad from none of it working. I have not successfully sent one e-mail yet. I've searched endlessly but I still have no idea what to do and why nothing is working.
At the moment I'm using Swiftmailer (second time round). I set up a test page with code:
<?php
require_once 'swift/lib/swift_required.php';
// CREATE TRANSPORT CONFIG
$transport = Swift_MailTransport::newInstance();
// CREATE MSG
$message = Swift_Message::newInstance();
// SET PRIORITY TO HIGH
$message->setPriority(2);
// SUBJECT
$message->setSubject('Subject');
// FROM
$message->setFrom(array('example#btopenworld.com'));
// TO
$message->setTo(array('example#googlemail.com'));
// EMAIL BODY
$message->setBody('Test');
// SEND
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
if (!$mailer->send($message, $failures)) {
echo "Failures:";
print_r($failures);
}
?>
Looking at a similar post someone suggested the last part of the code to see errors and my error is:
Failures:Array ( [0] => example#googlemail.com )
No matter what e-mail I change it to (all using e-mails I have, so real e-mails) it doesn't work. If anyone has any help or suggestions it would be hugely appreciated.
example#btopenworld.com
Unless you are using a btopenworld server to send the E-Mail from, this is not going to work. The E-Mails from address needs to be associated with the server you are sending the message from. You can put the BT address into the reply-to header.
Also, SwiftMailer should have a "debug" switch telling you exactly what goes wrong, but I can't find it in the docs right now. Here is a logger plugin for Swiftmailer that should help if all else fails.
Related
I've been trying for a while to get my emails to send using SendGrid. I've set up a test PHP script:
<?php
require_once('../resources/functions/sendgrid/lib/SendGrid.php');
SendGrid::register_autoloader();
require_once('../resources/functions/unirest/lib/Unirest.php');
$sendgrid = new SendGrid('my_username', 'my_password');
$sendgrid_email = new SendGrid\Email();
$sendgrid_email->addTo('my_email#gmail.com')->
setFrom('Name <noreply#my_domain.co.uk>')->
setSubject('Name | Test Mail')->
setText("TEST MESSAGE");
$sendgrid->smtp->send($sendgrid_email);
echo 'mail sent';
?>
I've tried this using both the web and smtp methods, both methods get to the "mail sent" echo, yet neither actually appear in my inbox, and when I check my SendGrid account I still have 0 sent emails.
EDIT:
Ok, so I got it working. Removed the "name ", changed it to just "noreply#my_domain.co.uk". However, I want to define the name using the first method - any way of doing this?
ANOTHER EDIT:
Alright, Nick Q's answer fixed the rest of the issues I was having. And for anyone who is wondering, the way you set a from name (i.e Example ) is by having setFrom as just the email [setFrom("noreply#example.com")] and then using setFromName [setFromName("Example")].
Call SendGrid::register_autoloader(); after also requiring Unirest.
Otherwise your script looks good.
I'm using SwiftMailer for PHP from swiftmailer.org
Everything works well but I wonder if there is a way to add the sent message into the sent folder from the mail account that SwiftMailer is sending from?
That's all, have a nice day.
According to the developer, swiftmailer cannot copy to Sent folder because it is a mail sender and not mailbox manager.
As mentioned on the github page:
Swiftmailer is a library to send emails, not to manage mailboxes. So, this is indeed out of the scope of Swiftmailer.
However, someone from php.net posted a solution that might work for you:
Use SwiftMailer to send the message via PHP.
$message = Swift_Message::newInstance("Subject goes here");
// (then add from, to, body, attachments etc)
$result = $mailer->send($message);
When you construct the message in step 1) above save it to a variable as follows:
$msg = $message->toString();
// (this creates the full MIME message required for imap_append()!!
// After this you can call imap_append like this:
imap_append($imap_conn,$mail_box,$msg."\r\n","\\Seen");
I've had similar problem and Sutandiono's answer got me into right direction. However because of completeness and as I had additional problem connecting to an Exchange 2007 server, I wanted to provide a complete snippet for storing message to Sent folder on IMAP:
$msg = $message->toString();
// $message is instance of Swift_Message from SwiftMailer
$stream = imap_open("{mail.XXXXX.org/imap/ssl/novalidate-cert}", "username", "password", null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
// connect to IMAP SSL (port 993) without Kerberos and no certificate validation
imap_append($stream,"{mail.XXXXX.org/imap/ssl/novalidate-cert}Sent Items",$msg."\r\n","\\Seen");
// Saves message to Sent folder and marks it as read
imap_close($stream);
// Close connection to the server when you're done
Replace server hostname, username and password with your own information.
I need to send over 2000 mails and I am using Swift Mailer library for it.
We have own server and it has both SMTP and sendmail transports. I am using SMTP:
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
All mails are send fine to few people, but I'm afraid that we will be banned when we send mass mail.
I don't really know what means "banned" and how it looks like, but I'm afraid about the aftermath.
So, is it true, that such "ban" exists and how to implement mass mailing with Swift Mailer in a right way?
P.S.: My code looks like:
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance($message_theme)
->setFrom(array($sender => $name))
->setTo($emails)
->setBody($message_text,"text/html")
;
try {
// Send the message
$result = $mailer->send($message);
}
catch(Exception $e) {
echo "Error: ".$e->getMessage();
}
As I'm hoping you will not use this for spam!!!
Here are some things to do:
try to same different Emails (change name of the recipient in body)
send emails once every 3-4 seconds and not 100 emails/second - it should send 2000 emails in about 2-3 hours.
Blacklisting/graylisting does indeed exist and there are some best practices you can implement to try to avoid these issues. For 2,000 emails, as long as your headers are legitimate, there is nothing fishy going on in your body text, and your recipients are on different domains, you should not run into this issue. However, as khomyakoshka mentions, the above code is incorrect and you should use a loop to send each email. This avoids exposing your entire mail list to each user.
Some additional best practices:
1) Swiftmailer offers plugins (http://swiftmailer.org/docs/plugins.html) that will help you send bulk email. Of particular note are the Throttler and AntiFlood plugins.
2) If you intend on modifying the contents of the mail to tailor to the recipient, consider using the Decorator plugin (also mentioned on the plugins page) for this task.
Hope these tips help.
I'm getting this error when trying to send an email using swiftmailer and the sendgrid smtp
Fatal error: *Uncaught exception 'Swift_TransportException' with message 'Expected response code 250 but got code "", with message ""'*
Here's my code :
$hdr = new SmtpApiHeader();
// Set all of the above variables
$hdr->addTo($toList);
$hdr->addSubVal('-name-', $nameList);
$hdr->addSubVal('-time-', $timeList);
// Specify that this is an initial contact message
$hdr->setCategory("initial");
// The subject of your email
$subject = 'Example SendGrid Email';
// Where is this message coming from. For example, this message can be from
// support#yourcompany.com, info#yourcompany.com
$from = array('no-reply#mupiz.com' => 'Mupiz');
$to = array('antonin#noos.fr'=>'AN',"antonin#mupiz.com"=>"AN2s");
$text="Hello -name-
Thank you for your interest in our products. We have set up an appointment
to call you at -time- EST to discuss your needs in more detail.
Regards,
Fred, How are you?
";
$html = "
<html>
<head></head>
<body>
<p>Hello -name-,<br>
Thank you for your interest in our products. We have set up an appointment
to call you at -time- EST to discuss your needs in more detail.
Regards,
Fred, How are you?<br>
</p>
</body>
</html>
";
// Your SendGrid account credentials
$username = 'XXXX';
$password = 'XXXX';
// Create new swift connection and authenticate
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 25);
$transport ->setUsername($username);
$transport ->setPassword($password);
$swift = Swift_Mailer::newInstance($transport);
// Create a message (subject)
$message = new Swift_Message($subject);
// add SMTPAPI header to the message
// *****IMPORTANT NOTE*****
// SendGrid's asJSON function escapes characters. If you are using Swift Mailer's
// PHP Mailer functions, the getTextHeader function will also escape characters.
// This can cause the filter to be dropped.
$headers = $message->getHeaders();
$headers->addTextHeader('X-SMTPAPI', $hdr->asJSON());
// attach the body of the email
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
// send message
if ($recipients = $swift->send($message, $failures))
{
// This will let us know how many users received this message
// If we specify the names in the X-SMTPAPI header, then this will always be 1.
echo 'Message sent out to '.$recipients.' users';
}
// something went wrong =(
else
{
echo "Something went wrong - ";
print_r($failures);
}
An idea ?
Thanks
There could be a number of things causing this. The most likely one is that your server has connecting to external hosts turned off. Other possibilities are that you're using an old version of PHP that has an openSSL error or that you're being rate limited by something.
You should take a look at this question for details on the external host issue: send mails via sendgrid
On a separate note, you should use the SendGrid PHP library if you want to send emails using SendGrid. It addresses a whole bunch of subtle nuances with Swift and sending in general. Also, it gives you access to the HTTP API in case you can't use SMTP for whatever reason.
https://github.com/sendgrid/sendgrid-php
Full Disclosure: I work as a developer evangelist for SendGrid and work on the PHP library from time to time.
for sendgrid might be two resons:
you may have the authentification data wrong
your account might still be provisioned, so you must wait a bit for it to be fully activated
so
check all the autentification data from app/config/mail.php to match with the data from https://sendgrid.com/docs/Integrate/index.html
check also not the have a top message/notification on your sendgrid account like:
Your account is still being provisioned, you may not be able to send
emails.
You will also receive this error if your account is frozen for billing reasons (e.g. lapsed credit card expiry date).
Note: SendGrid doesn't drop the message(s), they hold them until your billing issue is resolved then process them even when this error is returned.
This question should have a simple, simple answer, but I just can't seem to get it working. Here's the scenario:
I created a php page -> this one: http://adianl.ca/pages/member_application.php. Once the form is completed, it proceeds to http://adianl.ca/pages/member_application_action.php, puts the data into a MySQL db, & thanks the user for their interest. Anyway, the form works perfectly, except for one little thing: whenever someone fills out that form, I want an email to be sent to sbeattie#adianl.ca, informing them that the form was filled out, & the email would include the form components. The problem is, I can NOT get an email to be sent to that address, or any address truth be told. Having a php page send an email should be a simple thing to do, but it's really baffling me.
Can anyone help me with this? This particular problem has been troubling me since yesterday, & if anyone can help me with this...man, thank you soooooo much.
JP
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.adianl.ca"; // SMTP server $mail->From = "webadmin#adianl.ca";
$mail->FromName = "Web Administration [ADIANL]";
$mail->AddAddress("sbeattie#adianl.ca");
$mail->AddCC("justinwparsons#gmail.com"); the #messageBody variable is just a string
If you want to have the email sent using the server's sendmail client, you can use mail.
If you want it to use another mail server, there are extensions to connect to an SMTP server. I use PHPMailer.
If mail doesn't work, it could be that the server is not set up to send email, or it could be that the mail server is rejecting emails sent from php, amongst other reasons.
this code can also be used to email in php so have a look, you can find many more examples of emailing in php look around
?php
$to = "recipient#example.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body)) {
echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}