Sending Email through GMail

In my last 2 posts I have shown you how to send SMTP email using Java.
But I still haven’t shown how to send an Email through a secured SMTP server.

To do so I’ll show you how to use GMail secured SMTP server to send Emails.

Take a look at this class:


	public GMail() {
		try {
			String from = "everyDayDeveloper";
			String to = "aviyehuda@gmail.com";
			String body = "bla bla ...";
			String subject = "gmail"; 
			String senderEmail = "aaa@gmail.com";
			String senderPassword = "myPassword";
			
			MimeMessage message = new MimeMessage(getGmailSession());
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, 
			  new InternetAddress(to));
			message.setSubject(subject);
			message.setText(body);
	
			Transport.send(message);
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}
	
	public static Session getGmailSession()	{
			Properties props = System.getProperties();
			props.put("mail.smtp.host", "smtp.gmail.com");
	        props.put("mail.smtp.auth", "true");
	        props.put("mail.debug", "true");
	        props.put("mail.smtp.port ", "465");
	        props.put("mail.smtp.socketFactory.port", "465");
	        props.put("mail.smtp.socketFactory.class",
                              "javax.net.ssl.SSLSocketFactory");
	        props.put("mail.smtp.socketFactory.fallback", "false");
	        Session session = 
                    Session.getDefaultInstance(props, 
                               new javax.mail.Authenticator() {
	 protected PasswordAuthentication getPasswordAuthentication() {
	    return new PasswordAuthentication(senderEmail, senderPassword);
	             }
	        }
	        );
	        
	        return session;
	}

The basic is the same, like sending a simple SMTP message.

What’s different here is the creation of the Session object in the function getGmailSession().

The Session object is created with much more properties and with the Authenticator which holds the authentication properties.

You will also need the mail.jar that can be found here.

downloaddownload source

Leave a Reply

Your email address will not be published.