We are Web Technology Experts Team who provide you Important information on Web Development, Interview Questions and Answers, live project problem and their solution and online free tutorials.
Step 1:
Use Following code to send an email from Gmail Account.
// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Email Sender
$mail->setFrom('from@example.com', 'Mailer');
//Recipients
$mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen@example.com'); // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
//Attachments (IF there is attachment then only include)
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML (true)
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
If you get similar to following Error Please log in via your web browser and then try again. 5.7.14 Please log in via your web browser and then try again. 5.7.14 Learn more at 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 fr13sm3613053pdb.81
If Yes, whether you have "turned on 2-Step Verification" OR Google need Verification that you want to use your gmail as SMTP credential. You can fix this in couple of minutes using below link: https://support.google.com/mail/answer/78754
If any issue, please comment below in comment box:
During the website development, many times we need to check the Registration Process, Forget Password and Newsletter Functionalists etc, to Perform all these things we need number of number address. Its very hard to do registration in gmail.com OR yahoo.com OR hotmail.com everytime. You can get email address and at Free of cost within a second. Following are list of websites who provide email account and at free of cost.
SMTP Credentials like SMTP USRNAME, SMTP PASSWORD, SMTP HOST, SMTP PORT
Script Code
$toEmail='toemailaddress@domain.com'; //Receiver email address
$subject='Email with attachment';//Email subject
$htmlEmail='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eget nibh consectetur, mattis mauris vitae, aliquam orci. Nunc pretium tristique metus eget pharetra. Ut condimentum purus in ex varius, quis bibendum ex venenatis. Praesent leo lacus, feugiat vel neque ac, finibus ultricies velit. Nunc venenatis sem eu ullamcorper interdum. Fusce a pulvinar risus, quis viverra nulla. Donec tempus ex congue mauris elementum, eget fermentum orci dapibus. Proin erat lacus, lacinia eu volutpat quis, sagittis suscipit erat. Maecenas nulla enim, tempor ac urna id, tincidunt consectetur metus. Maecenas tincidunt, tortor quis sodales rutrum, purus mi accumsan libero, id maximus purus leo id ante. In posuere erat ipsum, sed mattis est placerat eget. Phasellus consectetur diam augue, sed luctus libero consequat quis. Praesent vel mauris nec ligula malesuada faucibus. Suspendisse ultrices nunc velit, in ultricies nibh tempus id. Integer quis nisi ipsum.'
. 'This is html email.';
//Email Configuration
$config = array(
'auth' => 'login',
'ssl' => 'tls',
'port' => '587',
'username' => 'MAIL_USERNAME',
'password' => 'MAIL_PASSWORD'
);
$tr = new Zend_Mail_Transport_Smtp('MAIL_HOST', $config);
Zend_Mail::setDefaultTransport($tr);
$mail = new Zend_Mail('UTF-8');
$mail->setFrom(MAIL_SENDER_EMAIL, MAIL_SENDER_NAME);
$mail->addTo($toEmail);
$mail->setSubject($subject);
$mail->setBodyHtml($htmlEmail);
//Attachment Email
//Get the contents of csv file
$csvContent= file_get_contents('http://example.com/projects/export-csv.csv');
$at = new Zend_Mime_Part($csvContent);
$at->type = 'text/csv';
$at->disposition = Zend_Mime::DISPOSITION_INLINE;
$at->encoding = Zend_Mime::ENCODING_BASE64;
$at->filename = 'csv-file.csv';
//Attach the attachment in Email
$mail->addAttachment($at);
//Send Email
$mail->send();
Question: How to send image as attachment in Email?
Following are attachment code.
$username = 'mygmail@gmail.com'; //Gmail address
$password = 'gma12#@c'; //Gmail password
error_reporting(0);
$bodyId=35; //This is message Id
//Read Message from indebox
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
//Read Message from Trash
// $hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Trash';
//Read Message from Sent
//$hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail';
$con = imap_open($hostname, $username, $password);
$messageNumber = $bodyId;
$structure = imap_fetchstructure($con, $messageNumber);
//pr($structure);die;
$message='';
if(!empty($structure->parts)){
$flattenedParts = flattenParts($structure->parts);
foreach($flattenedParts as $partNumber => $part) {
switch($part->type) {
case 0:
// the HTML or plain text part of the email
$message = getPart($con, $messageNumber, $partNumber, $part->encoding);
// now do something with the message, e.g. render it
break;
case 1:
// multi-part headers, can ignore
break;
case 2:
// attached message headers, can ignore
break;
case 3: // application
case 4: // audio
case 5: // image
case 6: // video
case 7: // other
//pr($part);
//echo "
$$$$$";
$filename = getFilenameFromPart($part);
if($filename) {
// it's an attachment
$attachment = getPart($con, $messageNumber, $partNumber, $part->encoding);
if (empty($filename))
$filename = $filename;
if (empty($filename))
$filename = time() . ".dat";
$folder = "attachment";
if (!is_dir($folder)) {
mkdir($folder);
}
$fp = fopen("./" . $folder . "/" . $messageNumber . "-" . $filename, "w+");
fwrite($fp, $filename);
fclose($fp);
// now do something with the attachment, e.g. save it somewhere
$message.='
Email functionalities in websites is very common and used in mostly in all web application. Whether it is registration process or Order detail, we need to send an email to your valuable client.
To send the email using Email Template follow the following steps 1. First collect all the data which you want to send in Email like first name, last name etc.
2. Create a Folder with name emails, where you can put the email templates files.
Email template Location: application/views/scripts/emails
3. Create a template with name registration.phtml for registration Email and add following contents.
First name: echo $data['fname'];
Last name: echo $data['fname'];
Folder Location: application/views/scripts/emails
Don't forget to add php scripts for php variable
Im just giving you an working code, you can add lot of variables as you need.
Add following code from where you want to send an email
$subject ='This is subject';
$view = new Zend_View();
$view->addScriptPath(APPLICATION_PATH . '/views/scripts/emails');
$view->data = $emailTemplateData; //$emailTemplateData must have the values which you are using in registration.phtml
$emailHtml = $view->render('registration.phtml');
$mail = new Zend_Mail();
$mail->setBodyHtml($emailHtml);
$mail->setSubject($subject);
$mail->setFrom("support@example.com", "From domain.com");
$mail->send();
If you get an issue regarding this post, Please comment below. we will try to fix your problem.
Sending an attachment in Email is very easy in zend framework. Attachmnet can be PDF file, image file, text and excel file etc. For Different type of attachment have different types of mime type. For example pdf mime type is "application/pdf" where gif image mime type is "image/gif".
In E-commerce website, when an order is placed by customer on the online website. Customer get the order detail in form of Order PDF File, So that he can keep offline record too.
Following code snippet is for How to attach a PDF file in Email using Zend Framework.
/** Must fill Following detail * */
$emailTo = 'receipts@no-spam.ws';
$emailToName = 'receipts Name';
/** Must fill Following detail * */
$emailSubject = 'This is subject';
$emailBody = 'This is HTML Email Body';
$fromEmail = 'fromemail@no-spam.ws';
try {
$config = array(
'ssl' => 'tls',
'auth' => 'login',
'username' => 'SMTP_USERNAME',
'password' => 'SMTP_PASSWORD'
);
$transport = new Zend_Mail_Transport_Smtp('SMTP_HOST', $config);
$mail = new Zend_Mail();
$mail->setBodyHtml($emailBody);
$mail->setFrom($fromEmail);
$mail->addTo($emailTo, $emailToName);
$mail->setSubject($emailSubject);
/**PDF Add Attachment **/
$attachment = new Zend_Mime_Part('path to pdf file');
$attachment->type = 'application/pdf';
$attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = Zend_Mime::ENCODING_BASE64;
$attachment->filename = 'order.pdf';
$mail->addAttachment($attachment);
/** Add Attachment **/
if ($mail->send($transport)) {
echo 'Sent successfully';
} else {
echo 'unable to send email';
}
} catch (Exception $e) {
echo $e->getMessage();
}
In Websites, we need to send email on Registration, Forget password, order to our Clients/Customer. If your email template is ready Sending email is a very quick step in WordPress, but sometimes developer gets confused due to not available of correct email sending code.
In this post, We will give you code snippet. This code snippet will send email. You can set the receipt, subject, description, reply-to and header in email.
$receipt = "user@no-spam.ws";
$subject = "This is subject";
$content = 'This is conent of the email.
http://www.web-technology-experts-notes.in';
/** Set the Reply -optional field **/
$headers = array(
'Reply-To' => "replyto@no-spam.ws"
);
/** Set the Reply -optional field **/
/** Send the Html email - optional field **/
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
/** Send the Html email - optional field **/
$status = wp_mail($receipt, $subject, $content, $headers);
In websites, We send email to our clients for Following:
- Registration Email
- Forget Password
- Change Password
- Notification Email
- Newsletter
- Order completed
- Order In transist
- Order deliver Successfully
Following code, Which can be used to send email in Zend-Framework (HTML EMAIL).
/** Must fill Following detail * */
$emailTo = 'receipts@no-spam.ws';
$emailToName = 'receipts Name';
/** Must fill Following detail * */
$emailSubject = 'This is subject';
$emailBody = 'This is HTML Email Body';
$fromEmail = 'fromemail@no-spam.ws';
In Website we need to send email on Registration, Forget , Order email to our Clients/Customer.
We want email should be deliver timely in inbox folder not in junk/spam folder.
For this we have to use SMTP Server.
GMAIL SMTP Server is free to use, if you have valid Gmail account.
Just the following code to send email from your Gmail Account.
/** Must fill Following detail * */
$yourGmailAccountUsername = 'youremail@gmail.com';
$yourGmailAccountPassword = '********';
$emailTo = 'arun.compute@gmail.com';
$emailToName = 'receiptsName';
/** Must fill Following detail * */
/** Optional Detail * */
$emailBody = 'This is body text';
$emailSubject = 'This is subject';
/** Optional Detail * */
try {
$config = array('ssl' => 'tls',
'auth' => 'login',
'username' => $yourGmailAccountUsername,
'password' => $yourGmailAccountPassword);
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
$mail = new Zend_Mail();
$mail->setBodyHtml($emailBody);
$mail->setFrom($yourGmailAccountUsername);
$mail->addTo($emailTo, $emailToName);
$mail->setSubject($emailSubject);
if ($mail->send($transport)) {
echo 'Sent successfully';
} else {
echo 'unable to send email';
}
} catch (Exception $e) {
echo $e->getMessage();
}
If you get similar to following Error Please log in via your web browser and then try again. 5.7.14 Please log in via your web browser and then try again. 5.7.14 Learn more at 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 fr13sm3613053pdb.81
If Yes,
whether you have "turned on 2-Step Verification" OR Google need Verification that you want to use your gmail as SMTP credential.
you can fix this in couple of minutes using below link: https://support.google.com/mail/answer/78754
If any issue, please comment below in comment box:
Images in HTML emails
a. Avoid spacer images
b. Always include the dimensions of your image
c. Avoid PNGs image
d. Always add alt text in image attribute
Simple Mail Transfer Protocol is an Internet standard for email transmission across Internet Protocol networks.
SMTP was first defined by RFC 821 (1982), It use TCP port 25.
SMTP was updated by RFC 5341(2008), It use TCP587. It is known as ESMTP and is the protocol in widespread use today.
Mail server and other transfer agent use SMTP to send & receive email. whereas User level client mail application use SMTP to send an email and for receiving email they use Post Office Protocol (POP) or the Internet Message Access Protocol (IMAP) or aLotus Notes/Domino to access their mail box accounts on a mail server.
Email is submitted by a mail client (MUA, mail user agent) to a mail server (MSA, mail submission agent) using SMTP on TCP port 587.
MSA delivers the mail to its mail transfer agent (MTA, mail transfer agent).