The Pursuit of Happyness

반응형

예전에 포스팅했던 [PHP] Gmail SMTP를 이용하여 메일 보내기를 업데이트 합니다.



먼저 예전에 구글코드에서 관리하던 PHPMailer는 github를 통해서 소스가 관리되고 있습니다.


현재 릴리즈 된 버전은 6.x 인데, composer로 설치할 경우 PHP 버전에 따라서 5.2.x 버전이 설치되기도 합니다.


모듈을 로딩하는 방식이 조금 다르기 때문에 버전에 따라 사용법을 살펴보겠습니다.



0. PHP 는 설치되어 있다고 가정합니다.


1. PHPMailer를 설치하기 위해서 composer를 설치합니다.


참고 사이트

https://getcomposer.org/download/


CLI 설치 

$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

$ php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

$ php composer-setup.php

$ php -r "unlink('composer-setup.php');"


위의 명령들을 차례대로 실행하면, 명령어를 실행한 경로에 composer.phar 파일이 생성됩니다.


2. PHPMailer 설치 


참고 사이트

https://github.com/PHPMailer/PHPMailer   (최신 버전)

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable  (5.2 버전)


composer.phar 파일이 있는 곳에서 다음의 명령으로 phpmailer 를 설치합니다.

$ php composer.phar require phpmailer/phpmailer


php 버전에 따라서 호환이 되는 PHPMailer 모듈이 설치됩니다.



3. 메일 보내기


6.x 버전에서는 사이트에 나와있는 샘플대로 아래와 같이 코드를 작성하면 됩니다. 

 

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
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

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $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
    $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
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $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.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}


5.2.x 버전에서도 기존 사이트에 나와있는 샘플과 비슷하게 작성하면됩니다.

(샘플에서 require 부분의 경로만 살짝 변경해 주었습니다.)


<?php
require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php'; $mail = new PHPMailer; //$mail->SMTPDebug = 3; // 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 $mail->setFrom('from@example.com', 'Mailer'); $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'); $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } 







반응형

반응형

CENTOS 6.4 / PHP 5.3.3

VBbulletin 사용 도중 서버 이전 후 메일이 발송되지 않는 문제가 발생해서 원인을 찾아보니,

로그에 아래와 같은 경고 메시지가 뜨면서 발송이 되지 않고 있었음.


Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.google.com (Permission denied) in /xxxx.php on line xx


원인

대부분의 경우 리눅스 보안설정 SELinux 에서 httpd 에서 네트워크 커넥션을 허용하지 않는 경우이다.


해결책

커맨드 프롬프트에서 다음과 같이 입력 

setsebool httpd_can_network_connect=1

(혹시 setsebool이 path가 결려있지 않은 경우 /usr/sbin/setsebool 을 이용)





반응형

반응형


import java.util.Properties;


import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;


public class GmailSMTP

{

    public static void sendMail(String account, String auth, String to, String subject, String msg, boolean isSSL, boolean isHtml)

    {

        final String username = account;

        final String password = auth;


        String mailFrom = username;

        String mailTo = to;


        Properties props = new Properties();

        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", "smtp.gmail.com");


        if (isSSL)

        {

            props.put("mail.smtp.socketFactory.port", "465");

            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            props.put("mail.smtp.port", "465");

        }

        else

        {

            props.put("mail.smtp.starttls.enable", "true");

            props.put("mail.smtp.port", "587");

        }


        Session session = Session.getInstance(props, new javax.mail.Authenticator()

        {

            protected PasswordAuthentication getPasswordAuthentication()

            {

                return new PasswordAuthentication(username, password);

            }

        });


        try

        {

            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress(mailFrom));

            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));

            message.setSubject(subject);


            if (isHtml)

                message.setContent(msg, "text/html");

            else

                message.setText(msg);


            Transport.send(message);

        }

        catch (MessagingException e)

        {

            throw new RuntimeException(e);

        }

    }

}

 


ps. mail.jar 가 필요함


반응형

반응형


PHPMailer 에 대한 새로운 사용법을 새로운 포스트에 남겨두었습니다. 참고하세요.


1. 다음 링크에서 필요한 모듈을 다운로드 받는다. (PHPMailer)

http://code.google.com/a/apache-extras.org/p/phpmailer/

개발자가 코드를 github 로 옮겼습니다. 아래 링크에서 다운로드 받으세요..

=> https://github.com/PHPMailer/PHPMailer

 

2. 다운로드 받은 파일을 적당한 경로에 압축을 푼다.

ex)

/var/www/html/inc/PHPMailer

 

3. 메일 보낼 코드 작성

/var/www/html/mailSample.php

 

<?php

require_once("inc/PHPMailer/class.phpmailer.php");

 

$mail = new PHPMailer(true);

$mail->IsSMTP();

try {

  $mail->Host = "smtp.gmail.com";    // email 보낼때 사용할 서버를 지정

  $mail->SMTPAuth = true;              // SMTP 인증을 사용함

  $mail->Port = 465;                        // email 보낼때 사용할 포트를 지정

  $mail->SMTPSecure = "ssl";        // SSL을 사용함

  $mail->Username   = "GMAIL ACCOUNT";    // Gmail 계정

  $mail->Password   = "PASSWORD";            // 패스워드

 

  $mail->SetFrom('from email address', 'Display Name'); // 보내는 사람 email 주소와 표시될 이름 (표시될 이름은 생략가능)

  $mail->AddAddress('to email address', 'Display Name'); // 받을 사람 email 주소와 표시될 이름 (표시될 이름은 생략가능)

  $mail->Subject = 'Email Subject';        // 메일 제목

  $mail->MsgHTML("Email Content");    // 메일 내용 (HTML 형식도 되고 그냥 일반 텍스트도 사용 가능함)

 

  $mail->Send();                                // 실제로 메일을 보냄

  echo "Message Sent OK<p></p>\n";

} catch (phpmailerException $e) {

  echo $e->errorMessage(); //Pretty error messages from PHPMailer

} catch (Exception $e) {

  echo $e->getMessage(); //Boring error messages from anything else!

}

?>

 

 

 

반응형