SendMailUsingAuthentication.java
上传用户:szzhhli
上传日期:2022-02-01
资源大小:1k
文件大小:2k
源码类别:
Email客户端
开发平台:
Java
- //one need to configure 1. SMTP_AUTH_USER, 2. SMTP_AUTH_PWD in SMTPAuthenticator inner class; beside changing the 3. SMTP //server URL in GetProperties()
- //change 1. emailMsgTxt, 2. receiver in the postMail() to send different messages to different people
- package CheckIPAddress;
- import javax.mail.*;
- import javax.mail.internet.*;
- import java.util.*;
- import java.io.*;
- public class SendMailUsingAuthentication
- {
- MimeMessage msg = null;
- //change host as needed
- private Properties getProperties()
- {
- final String SMTP_HOST_NAME = "smtp.gmail.com"; //change host as needed
- Properties p = new Properties();
- p.put("mail.smtp.host", SMTP_HOST_NAME);//Set the host smtp address
- p.put("mail.smtp.starttls.enable","true");
- p.put( "mail.smtp.auth", "true"); //validate user
- return p;
- }
- public SendMailUsingAuthentication() throws MessagingException
- {
- final String emailSubjectTxt = "Your Password of new Registration";
- Session session = Session.getInstance(getProperties(),
- new Authenticator() //one need to configure 1. SMTP_AUTH_USER, 2. SMTP_AUTH_PWD
- {
- private final String SMTP_AUTH_USER = "saurabhcbk";
- private final String SMTP_AUTH_PWD = "saurabh123";
- public PasswordAuthentication getPasswordAuthentication()
- {
- return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
- }
- }
- );//validate user and create a session
- msg = new MimeMessage(session);
- msg.setSubject(emailSubjectTxt);
- }
- public int postMail( String receiver, String message )
- {
- int status=0;
- try
- {
- msg.setText(message); //email message body or content
- msg.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); //receiver mail id
- Transport.send(msg);
- System.out.println("Receiver: "+receiver+ "Message: " + msg.getContent()+" at "+ new java.util.Date().toString());
- status=1;
- }
- catch(Exception sendingError)
- {
- System.out.println("Sending mail has been failed");
- }
- return status;
- }
- }