This Java program will build a multi-part MIME email and send it through SendGrid. Java already has built in libraries to send and receive emails. This example uses javamail.
importjavax.mail.*;importjavax.mail.internet.*;importjavax.mail.Authenticator;importjavax.mail.PasswordAuthentication;importjava.util.Properties;publicclassSimpleMail{privatestaticfinalStringSMTP_HOST_NAME="smtp.sendgrid.net";privatestaticfinalStringSMTP_AUTH_USER="myusername";privatestaticfinalStringSMTP_AUTH_PWD="mypwd";publicstaticvoidmain(String[]args)throwsException{newSimpleMail().test();}publicvoidtest()throwsException{Propertiesprops=newProperties();props.put("mail.transport.protocol","smtp");props.put("mail.smtp.host",SMTP_HOST_NAME);props.put("mail.smtp.port",587);props.put("mail.smtp.auth","true");Authenticatorauth=newSMTPAuthenticator();SessionmailSession=Session.getDefaultInstance(props,auth);// uncomment for debugging infos to stdout// mailSession.setDebug(true);Transporttransport=mailSession.getTransport();MimeMessagemessage=newMimeMessage(mailSession);Multipartmultipart=newMimeMultipart("alternative");BodyPartpart1=newMimeBodyPart();part1.setText("This is multipart mail and u read part1......");BodyPartpart2=newMimeBodyPart();part2.setContent("<b>This is multipart mail and u read part2......</b>","text/html");multipart.addBodyPart(part1);multipart.addBodyPart(part2);message.setContent(multipart);message.setFrom(newInternetAddress("me@myhost.com"));message.setSubject("This is the subject");message.addRecipient(Message.RecipientType.TO,newInternetAddress("someone@somewhere.com"));transport.connect();transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));transport.close();}privateclassSMTPAuthenticatorextendsjavax.mail.Authenticator{publicPasswordAuthenticationgetPasswordAuthentication(){Stringusername=SMTP_AUTH_USER;Stringpassword=SMTP_AUTH_PWD;returnnewPasswordAuthentication(username,password);}}}