function test_email_settings() { if (isset($_POST['gmail_smtp_send_test_email'])) { $to = ''; if (isset($_POST['gmail_smtp_to_email']) && !empty($_POST['gmail_smtp_to_email'])) { $to = sanitize_text_field($_POST['gmail_smtp_to_email']); } $subject = ''; if (isset($_POST['gmail_smtp_email_subject']) && !empty($_POST['gmail_smtp_email_subject'])) { $subject = sanitize_text_field($_POST['gmail_smtp_email_subject']); } $message = ''; if (isset($_POST['gmail_smtp_email_body']) && !empty($_POST['gmail_smtp_email_body'])) { $message = sanitize_text_field($_POST['gmail_smtp_email_body']); } $options = gmail_smtp_get_option(); $mail = new PHPMailerOAuth(); /* this must be the custom class we created */ // Tell PHPMailer to use SMTP $mail->isSMTP(); // Enable SMTP debugging $mail->SMTPDebug = 4; // Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; // Set AuthType $mail->AuthType = 'XOAUTH2'; // Whether to use SMTP authentication $mail->SMTPAuth = true; // Set the encryption system to use - ssl (deprecated) or tls $mail->SMTPSecure = $options['type_of_encryption']; // Set the hostname of the mail server $mail->Host = 'smtp.gmail.com'; // Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission $mail->Port = $options['smtp_port']; // User Email to use for SMTP authentication - Use the same Email used in Google Developer Console $mail->oauthUserEmail = $options['oauth_user_email']; //Obtained From Google Developer Console $mail->oauthClientId = $options['oauth_client_id']; //Obtained From Google Developer Console $mail->oauthClientSecret = $options['oauth_client_secret']; $gmail_token = json_decode($options['oauth_access_token'], true); //Obtained By running get_oauth_token.php after setting up APP in Google Developer Console. //Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php // eg: http://localhost/phpmail/get_oauth_token.php $mail->oauthRefreshToken = $gmail_token['refresh_token']; //Set who the message is to be sent from $mail->setFrom($options['from_email'], $options['from_name']); //Set an alternative reply-to address //$mail->addReplyTo('*****@*****.**', 'James Scott'); //Set who the message is to be sent to $mail->addAddress($to); //Set the subject line $mail->Subject = $subject; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body //$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); $mail->Body = $message; $mail->SMTPAutoTLS = false; //send the message, check for errors if (!$mail->send()) { echo __('Mailer Error: ', 'gmail-smtp') . $mail->ErrorInfo; } else { echo __('Message sent!', 'gmail-smtp'); } } ?> <form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?> "> <?php wp_nonce_field('gmail_smtp_test_email'); ?> <table class="form-table"> <tbody> <tr valign="top"> <th scope="row"><label for="gmail_smtp_to_email"><?php _e('To', 'gmail-smtp'); ?> </label></th> <td><input name="gmail_smtp_to_email" type="text" id="gmail_smtp_to_email" value="" class="regular-text"> <p class="description"><?php _e('Email address of the recipient', 'gmail-smtp'); ?> </p></td> </tr> <tr valign="top"> <th scope="row"><label for="gmail_smtp_email_subject"><?php _e('Subject', 'gmail-smtp'); ?> </label></th> <td><input name="gmail_smtp_email_subject" type="text" id="gmail_smtp_email_subject" value="" class="regular-text"> <p class="description"><?php _e('Subject of the email', 'gmail-smtp'); ?> </p></td> </tr> <tr valign="top"> <th scope="row"><label for="gmail_smtp_email_body"><?php _e('Message', 'gmail-smtp'); ?> </label></th> <td><textarea name="gmail_smtp_email_body" id="gmail_smtp_email_body" rows="6"></textarea> <p class="description"><?php _e('Email body', 'gmail-smtp'); ?> </p></td> </tr> </tbody> </table> <p class="submit"><input type="submit" name="gmail_smtp_send_test_email" id="gmail_smtp_send_test_email" class="button button-primary" value="<?php _e('Send Email', 'gmail-smtp'); ?> "></p> </form> <?php }
<?php /** * This example shows settings to use when sending via Google's Gmail servers. */ //SMTP needs accurate times, and the PHP time zone MUST be set //This should be done in your php.ini, but this is how to do it if you don't have access to that date_default_timezone_set('Etc/UTC'); require '../PHPMailerAutoload.php'; //Load dependencies from composer //If this causes an error, run 'composer install' require '../vendor/autoload.php'; //Create a new PHPMailer instance $mail = new PHPMailerOAuth(); //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = 'smtp.gmail.com'; //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission $mail->Port = 587; //Set the encryption system to use - ssl (deprecated) or tls $mail->SMTPSecure = 'tls'; //Whether to use SMTP authentication $mail->SMTPAuth = true;
function wp_mail($to, $subject, $message, $headers = '', $attachments = array()) { // Compact the input, apply the filters, and extract them back out /** * Filter the wp_mail() arguments. * * @since 2.2.0 * * @param array $args A compacted array of wp_mail() arguments, including the "to" email, * subject, message, headers, and attachments values. */ $atts = apply_filters('wp_mail', compact('to', 'subject', 'message', 'headers', 'attachments')); if (isset($atts['to'])) { $to = $atts['to']; } if (isset($atts['subject'])) { $subject = $atts['subject']; } if (isset($atts['message'])) { $message = $atts['message']; } if (isset($atts['headers'])) { $headers = $atts['headers']; } if (isset($atts['attachments'])) { $attachments = $atts['attachments']; } if (!is_array($attachments)) { $attachments = explode("\n", str_replace("\r\n", "\n", $attachments)); } $options = gmail_smtp_get_option(); $phpmailer = new PHPMailerOAuth(); /* this must be the custom class we created */ // Tell PHPMailer to use SMTP $phpmailer->isSMTP(); // Set AuthType $phpmailer->AuthType = 'XOAUTH2'; // Whether to use SMTP authentication $phpmailer->SMTPAuth = true; // Set the encryption system to use - ssl (deprecated) or tls $phpmailer->SMTPSecure = $options['type_of_encryption']; // Set the hostname of the mail server $phpmailer->Host = 'smtp.gmail.com'; // Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission $phpmailer->Port = $options['smtp_port']; $phpmailer->SMTPAutoTLS = false; //enable debug when sending a test mail if (isset($_POST['gmail_smtp_send_test_email'])) { $phpmailer->SMTPDebug = 4; // Ask for HTML-friendly debug output $phpmailer->Debugoutput = 'html'; } //disable ssl certificate verification if checked if (isset($options['disable_ssl_verification']) && !empty($options['disable_ssl_verification'])) { $phpmailer->SMTPOptions = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)); } // User Email to use for SMTP authentication - Use the same Email used in Google Developer Console $phpmailer->oauthUserEmail = $options['oauth_user_email']; //Obtained From Google Developer Console $phpmailer->oauthClientId = $options['oauth_client_id']; //Obtained From Google Developer Console $phpmailer->oauthClientSecret = $options['oauth_client_secret']; $gmail_token = json_decode($options['oauth_access_token'], true); //Obtained By running get_oauth_token.php after setting up APP in Google Developer Console. //Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php // eg: http://localhost/phpmail/get_oauth_token.php $phpmailer->oauthRefreshToken = $gmail_token['refresh_token']; // Headers if (empty($headers)) { $headers = array(); } else { if (!is_array($headers)) { // Explode the headers out, so this function can take both // string headers and an array of headers. $tempheaders = explode("\n", str_replace("\r\n", "\n", $headers)); } else { $tempheaders = $headers; } $headers = array(); $cc = array(); $bcc = array(); // If it's actually got contents if (!empty($tempheaders)) { // Iterate through the raw headers foreach ((array) $tempheaders as $header) { if (strpos($header, ':') === false) { if (false !== stripos($header, 'boundary=')) { $parts = preg_split('/boundary=/i', trim($header)); $boundary = trim(str_replace(array("'", '"'), '', $parts[1])); } continue; } // Explode them out list($name, $content) = explode(':', trim($header), 2); // Cleanup crew $name = trim($name); $content = trim($content); switch (strtolower($name)) { // Mainly for legacy -- process a From: header if it's there case 'from': $bracket_pos = strpos($content, '<'); if ($bracket_pos !== false) { // Text before the bracketed email is the "From" name. if ($bracket_pos > 0) { $from_name = substr($content, 0, $bracket_pos - 1); $from_name = str_replace('"', '', $from_name); $from_name = trim($from_name); } $from_email = substr($content, $bracket_pos + 1); $from_email = str_replace('>', '', $from_email); $from_email = trim($from_email); // Avoid setting an empty $from_email. } elseif ('' !== trim($content)) { $from_email = trim($content); } break; case 'content-type': if (strpos($content, ';') !== false) { list($type, $charset_content) = explode(';', $content); $content_type = trim($type); if (false !== stripos($charset_content, 'charset=')) { $charset = trim(str_replace(array('charset=', '"'), '', $charset_content)); } elseif (false !== stripos($charset_content, 'boundary=')) { $boundary = trim(str_replace(array('BOUNDARY=', 'boundary=', '"'), '', $charset_content)); $charset = ''; } // Avoid setting an empty $content_type. } elseif ('' !== trim($content)) { $content_type = trim($content); } break; case 'cc': $cc = array_merge((array) $cc, explode(',', $content)); break; case 'bcc': $bcc = array_merge((array) $bcc, explode(',', $content)); break; default: // Add it to our grand headers array $headers[trim($name)] = trim($content); break; } } } } // Empty out the values that may be set $phpmailer->ClearAllRecipients(); $phpmailer->ClearAttachments(); $phpmailer->ClearCustomHeaders(); $phpmailer->ClearReplyTos(); // From email and name // If we don't have a name from the input headers if (!isset($from_name)) { $from_name = $options['from_name']; //'WordPress'; } /* If we don't have an email from the input headers default to wordpress@$sitename * Some hosts will block outgoing mail from this address if it doesn't exist but * there's no easy alternative. Defaulting to admin_email might appear to be another * option but some hosts may refuse to relay mail from an unknown domain. See * https://core.trac.wordpress.org/ticket/5007. */ if (!isset($from_email)) { // Get the site domain and get rid of www. $sitename = strtolower($_SERVER['SERVER_NAME']); if (substr($sitename, 0, 4) == 'www.') { $sitename = substr($sitename, 4); } $from_email = $options['from_email']; //'wordpress@' . $sitename; } /** * Filter the email address to send from. * * @since 2.2.0 * * @param string $from_email Email address to send from. */ $phpmailer->From = apply_filters('wp_mail_from', $from_email); /** * Filter the name to associate with the "from" email address. * * @since 2.3.0 * * @param string $from_name Name associated with the "from" email address. */ $phpmailer->FromName = apply_filters('wp_mail_from_name', $from_name); // Set destination addresses if (!is_array($to)) { $to = explode(',', $to); } foreach ((array) $to as $recipient) { try { // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>" $recipient_name = ''; if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) { if (count($matches) == 3) { $recipient_name = $matches[1]; $recipient = $matches[2]; } } $phpmailer->AddAddress($recipient, $recipient_name); } catch (phpmailerException $e) { continue; } } // Set mail's subject and body $phpmailer->Subject = $subject; $phpmailer->Body = $message; // Add any CC and BCC recipients if (!empty($cc)) { foreach ((array) $cc as $recipient) { try { // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>" $recipient_name = ''; if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) { if (count($matches) == 3) { $recipient_name = $matches[1]; $recipient = $matches[2]; } } $phpmailer->AddCc($recipient, $recipient_name); } catch (phpmailerException $e) { continue; } } } if (!empty($bcc)) { foreach ((array) $bcc as $recipient) { try { // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>" $recipient_name = ''; if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) { if (count($matches) == 3) { $recipient_name = $matches[1]; $recipient = $matches[2]; } } $phpmailer->AddBcc($recipient, $recipient_name); } catch (phpmailerException $e) { continue; } } } // Set Content-Type and charset // If we don't have a content-type from the input headers if (!isset($content_type)) { $content_type = 'text/plain'; } /** * Filter the wp_mail() content type. * * @since 2.3.0 * * @param string $content_type Default wp_mail() content type. */ $content_type = apply_filters('wp_mail_content_type', $content_type); $phpmailer->ContentType = $content_type; // Set whether it's plaintext, depending on $content_type if ('text/html' == $content_type) { $phpmailer->IsHTML(true); } // If we don't have a charset from the input headers if (!isset($charset)) { $charset = get_bloginfo('charset'); } // Set the content-type and charset /** * Filter the default wp_mail() charset. * * @since 2.3.0 * * @param string $charset Default email charset. */ $phpmailer->CharSet = apply_filters('wp_mail_charset', $charset); // Set custom headers if (!empty($headers)) { foreach ((array) $headers as $name => $content) { $phpmailer->AddCustomHeader(sprintf('%1$s: %2$s', $name, $content)); } if (false !== stripos($content_type, 'multipart') && !empty($boundary)) { $phpmailer->AddCustomHeader(sprintf("Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary)); } } if (!empty($attachments)) { foreach ($attachments as $attachment) { try { $phpmailer->AddAttachment($attachment); } catch (phpmailerException $e) { continue; } } } /** * Fires after PHPMailer is initialized. * * @since 2.2.0 * * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference. */ //do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) ); // Send! try { return $phpmailer->Send(); } catch (phpmailerException $e) { return false; } }