This code helps us to send mail to the gmail account using java code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailTest { public static void main(String[] args) throws AddressException, MessagingException { String host = "smtp.gmail.com" ; String from = "username" ; String pass = "password" ; Properties props = System.getProperties(); props.setProperty( "proxySet" , "true" ); props.setProperty( "http.proxyHost" , "192.168.155.1" ); props.setProperty( "http.proxyPort" , "808" ); props.put( "mail.smtp.starttls.enable" , "true" ); // added this line props.put( "mail.smtp.host" , host); props.put( "mail.smtp.user" , from); props.put( "mail.smtp.password" , pass); props.put( "mail.smtp.port" , "587" ); props.put( "mail.smtp.auth" , "true" ); String[] to = { "to@gmail.com" }; // added this line Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage(session); message.setFrom( new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for ( int i= 0 ; i < to.length; i++ ) { // changed from a while loop toAddress[i] = new InternetAddress(to[i]); } System.out.println(Message.RecipientType.TO); for ( int i= 0 ; i < toAddress.length; i++) { // changed from a while loop message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject( "sending in a group" ); message.setText( "Welcome to JavaMail" ); Transport transport = session.getTransport( "smtp" ); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } } |