package com.java.myapp; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; 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 MyClass { public static void main(String[] args) { final String auth_host = "mail.thaicreate.com"; final String auth_port = "25"; final String auth_email = "[email protected]"; final String auth_password = "password"; Properties props = new Properties(); props.put("mail.smtp.host", auth_host); props.put("mail.smtp.socketFactory.port", auth_port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", auth_port); try { Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (auth_email,auth_password); } }); Message message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(auth_email)); // From /*** Recipient ***/ message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); // To message.setSubject("Test sending mail from Java"); // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); String Attach = "C:\\java\\data.txt"; //fill message messageBodyPart.setText("Hello mr.win, Please do not reply this mail"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(Attach); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("data.txt"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); System.out.println("Mail Send Successfully."); } catch (MessagingException e) { throw new RuntimeException(e); } } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท