본문 바로가기
LANG/java

java / sendmail

by 하하IT 2020. 4. 19.

1. java source

 

import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;

 

/** * This class is used to send simple email. * @author javawithease */

public class SendSimpleEmail {

final String senderEmailId = "aaa@bbb.com";

final String senderPassword = "****";

final String emailSMTPserver = "relayhost URL;

 

public SendSimpleEmail(String receiverEmail, String subject,

String messageText) {

Properties props = new Properties();

props.put("mail.smtp.auth", "false"); //해당 IP가 relay 허용이면 false여도 메일발송가능함

props.put("mail.smtp.host", emailSMTPserver);

try {

Authenticator auth = new SMTPAuthenticator();

Session session = Session.getInstance(props, auth);

Message message = new MimeMessage(session);

message.setFrom(new InternetAddress(senderEmailId));

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse(receiverEmail));

message.setSubject(subject);

message.setText(messageText);

Transport.send(message);

System.out.println("Email send successfully.");

} catch (Exception e) {

e.printStackTrace();

System.err.println("Error in sending email.");

}

}

 

private class SMTPAuthenticator extends javax.mail.Authenticator {

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(senderEmailId, senderPassword);

}

}

 

public static void main(String[] args) {

new SendSimpleEmail("받는사람메일주소"

, "Test Email",

"Hi,\n\n This is a test email."

);

}

}

 

2. compile

javac -cp javax.mail-1.5.1.jar  SendSimpleEmail.java

 

 

3. run 

java -cp javax.mail-1.5.1.jar:.  SendSimpleEmail