Cài Javamail 1.4.5: Java Code To Send Email Using Java Mail Using Gmail SMTP Server
Cài Javamail 1.4.5: Java Code To Send Email Using Java Mail Using Gmail SMTP Server
5
Java code to send Email using Java Mail using Gmail SMTP Server
Cc m sau y c s dng gi th JavaMail thng qua my ch gmail. JavaMail 1.4 c kh nng gi v c tin nhn bng cch s dng Gmail. V l do an ninh, Gmail cho php truy cp SMTP qua kt ni SSL. Vui lng ti v Javamail 1.4 v khai bo mailapi,jar, smtp.jar trong Classpath. import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.smtp.SMTPSSLTransport; public class SendMailExample { public static void main(String[] args) { String from = [email protected]; String to = [email protected]; String subject = Test Message; String message = This is A test message sent via Gmail ; SendMail sendMail = new SendMail(from, to, subject, message); sendMail.send(); } } class SendMail { private String from; private String to; private String subject; private String text; public SendMail(String from, String to, String subject, String text){this.from = from; this.to = to; this.subject = subject;this.text = text;} public String String String void send(){ host = smtp.gmail.com; userid = Gmail User Id; password = password of gmail id;
try { Properties props = System.getProperties(); props.put(mail.smtp.starttls.enable, true); props.put(mail.smtp.host, host); props.setProperty(mail.transport.protocol, smtps); props.put(mail.smtp.user, userid); props.put(mail.smtp.password, password); props.put(mail.smtp.port, 465); props.put(mail.smtps.auth, true); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(from); toAddress = new InternetAddress(to); } catch (AddressException e) { e.printStackTrace(); } message.setFrom(fromAddress); message.setRecipient(RecipientType.TO, toAddress); message.setSubject(subject); message.setText(text); //SMTPSSLTransport transport =(SMTPSSLTransport)session.getTransport(smtps); Transport transport = session.getTransport(smtps); transport.connect(host, userid, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } }
By daylaptrinh Posted in Java (J2SE J2EE J2ME) Tagged internetaddress, mail internet, mail
message, mail session,mail smtp, mail transport