Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Thursday, October 13, 2022

Java program to send email using smtp

 

  1. Send email using Gmail with Java program below
    Update the From email id,password and to email id with your email information.
    send_email_gmail.java

    package email;
    import java.util.*; 
    import javax.mail.*; 
    import javax.mail.PasswordAuthentication;
    import javax.mail.internet.*;
    public class send_email_gmail {
    	public static void main(String[] args) {
    		final String username = "fromemail@gmail.com";
    		final String password = "password";
    		Properties props = new Properties();
    		props.put("mail.smtp.auth", "true");
    		props.put("mail.smtp.starttls.enable", "true");
    		props.put("mail.smtp.host", "smtp.gmail.com");
    		props.put("mail.smtp.port", "587");
    		Session session = Session.getInstance(props,
    		  new javax.mail.Authenticator() {
    			protected PasswordAuthentication getPasswordAuthentication() {
    			return new PasswordAuthentication(username, password);
    			}
    		  });
    		try {
    			Message message = new MimeMessage(session);
    			message.setFrom(new InternetAddress("fromemail@gmail.com"));
    			message.setRecipients(Message.RecipientType.TO,
    			InternetAddress.parse("toemail@gmail.com"));
    			message.setSubject("Testing Subject");
    			message.setText("Dear Mail Crawler,"
    				+ "\n\n No spam to my email, please!"
    				+ "Visit https://honeyvig.com");
    			Transport.send(message);
    			System.out.println("Done");
    		} catch (MessagingException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
  2. If you run the send_email_gmail.java as Run as Java Application for first time. You will get the Exception as shown below.
    Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException
    	at email.send_email_gmail.main(send_email_gmail.java:45)
    Caused by: javax.mail.AuthenticationFailedException
    	at javax.mail.Service.connect(Service.java:319)
    	at javax.mail.Service.connect(Service.java:169)
    	at javax.mail.Service.connect(Service.java:118)
    	at javax.mail.Transport.send0(Transport.java:188)
    	at javax.mail.Transport.send(Transport.java:118)
    	at email.send_email_gmail.main(send_email_gmail.java:40)
    

    To solve the exception above you have to enable access to your google account for less secure accounts.
    You can do it here https://myaccount.google.com/lesssecureapps?rfn=27&rfnc=1&eid=-1863921138390796625&et=0&asae=2&pli=1

  3. Now if you Run the the send_email_gmail.java as Run as Java Application. The recipient will get below mail
  4. Send emails from other domains using java SMTP
    Run the below code as Java project. Update the email info with your email details.
    send_mail.java

    package email;
    import java.util.*; 
    import javax.mail.*;
    import javax.mail.Authenticator;
    import javax.mail.PasswordAuthentication;
    import javax.mail.internet.*;
    public class send_mail {
    	public static void main(String[] args) {
    		send_mail obj_send_mail=new send_mail();
    		obj_send_mail.send_mail("Message Body", "toemailid");
    	}
    	public void send_mail(String message,String email_id) {
    		String smtpServer = null; 
                    String smtpPort = null;
    		final String authAddress = "From Email ID";      
    		final String authPassword = "From email id password";    
    		String subject = "Subject Email ID";          
    		//String message = "test by jinu";     
            smtpServer = "SMTP Server";
            smtpPort = "587";    
            try{    
                    Properties props = new Properties();     
                    props.put("mail.smtp.host", smtpServer); 
                    props.put("mail.smtp.port", smtpPort);   
                    props.put("mail.smtp.auth", "true");         
                // create some properties and get the default Session
                Session sessionMail = Session.getInstance(props, new Authenticator() {
                     public PasswordAuthentication getPasswordAuthentication() {      
                             return new PasswordAuthentication(authAddress, authPassword);
                     }                                                                    
                    });                                                                   
                sessionMail.setDebug(true);
                // create a message
                Message msg = new MimeMessage(sessionMail);
                // set the from and to address
                InternetAddress addressFrom = new InternetAddress(authAddress);
                msg.setFrom(addressFrom);
                InternetAddress[] addressTo = new InternetAddress[1];
                addressTo[0] = new InternetAddress(email_id);
                msg.setRecipients(Message.RecipientType.TO, addressTo);
                // Optional : You can also set your custom headers in the Email if you Want
                msg.addHeader("site", "honeyvig.com");
                // Setting the Subject and Content Type
                msg.setSubject(subject);
                msg.setContent(message, "text/html");
                Transport.send(msg);
            }catch(Exception e){
                    System.out.println(e);
            }
    }
    }
    

No comments:

Post a Comment