ตัวอย่าง Class การส่ง E-Mail ด้วย Java
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail {
// ################# E-Mail Information Section ################
private static String SMTP_HOST_NAME = "127.0.0.1"; //ขึ้นอยู่กับผู้ให้บริการ
private static String SMTP_PORT = "25";//ขึ้นอยู่กับผู้ให้บริการ
private static String FROM = "Java_Department";
private static String TO = "sakorn234@gmail.com";
private static String CC = "sakorn234@gmail.com";
private static String SUBJECT = "Test send email.";
private static String MESSAGE = "Test Body Text.";
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", SMTP_PORT);
Session session = Session.getInstance(props, null);
session.setDebug(false);
Date now = new Date();
boolean ckSendMail = false;
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM));
InternetAddress[] to_address = InternetAddress.parse(TO);
InternetAddress[] cc_address = InternetAddress.parse(CC);
message.setRecipients(Message.RecipientType.TO, to_address);
message.setRecipients(Message.RecipientType.CC, cc_address);
message.setSubject(SUBJECT);
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(MESSAGE, "UTF-8");
mbp.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
Multipart content = new MimeMultipart();
content.addBodyPart(mbp);
message.setContent(content);
Transport.send(message);
ckSendMail = true;
} catch (MessagingException mex) {
System.out.println("\n--Exception handling in msgsendsample.java");
System.out.println(now + " :: ==>> " + mex);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ckSendMail){
System.out.println("Send E-Mail Success..");
}else {
System.out.println("Send E-Mail Fail..");
}
System.out.println("Run Mail Done...");
}
}
}
Output
Send E-Mail Success..
Run Mail Done...
ข้อให้สนุกกับการส่ง E-Mail นะครับ