How to Send Emails With Java Using Gmail Accounts

It’s actually quite simple on how to send emails using java, only need several lines of codes. This is how i do it

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

public class MailTestSend {

    private static Logger logger = Logger.getLogger(MailTestSend.class);

    public static void main(String[] args) {
        try {

            // setup the mail server properties
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");

            // set up the message
            Session session = Session.getInstance(props);

            Message message = new MimeMessage(session);

            // add a TO address
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(""));

            // add a multiple CC addresses
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(","));
            message.setSubject("Welcome to Java");
            message.setContent("Hi, im testing a new way to send emails via java.", "text/plain");

            Transport transport = session.getTransport("smtp");
            transport.connect("", 587, "yourgmailusername", "yourgmailpassword");
            transport.sendMessage(message, message.getAllRecipients());
            logger.error("successfully send email");
        } catch (Exception e) {            
            logger.error(e, e);

Please dont forget to include mail.jar into your project. This is the screenshot of my netbeans libraries and my email inbox.





about 4 years ago

assalamualaikum , mas edwin saya mau tanya . saya udah ikutin tutoria mas tentang ngirim email pake gmail acc, tp ada output seperti ini : log4j:WARN No appenders could be found for logger (email.sendGmail). log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL (total time: 4 seconds) mohon penjelasan lebih lanjut. terima kasih



about 4 years ago

Waalaikumsalam erni.essa, itu adalah warning karena kamu engga ada coba cek di postingan gw sebelumnya, ada bagaimana konfigurasi Tetapi kamu jangan takut, aplikasi kamu tetap berjalan lancar walaupun tanpa

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked

:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)