tags:

views:

14851

answers:

10

Is it possible to send an email from my Java application using a Gmail account? I have it configured to send using my company mail server, but that's not going to cut it when I distribute the application. Answers using Hotmail or Yahoo mail are also acceptable.

A: 

You can connect to Gmail via SMTP, and its pretty easy to send mail via an smtp connection in java. I would go that route.

shsteimer
A: 

An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers.

Then you'd just send through smtp.gmail.com (on port 587)

Ryan Farley
+1  A: 

Here's a post on Suns' site on how to do this...

http://forums.sun.com/thread.jspa?threadID=591321&messageID=3750881

Ryan Lanciaux
+22  A: 

Something like this (sounds like you just need to change your SMTP server):

String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
    i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
    i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
jodonnell
+21  A: 

Thanks to jodonnel and everyone else who answered. I'm accepting his answer because it was about 95% complete. Here's the final code that I got to work (with comments where I needed to make changes). You'd only have to change the from, pass, and to fields to make it work. from and pass take the username and password that you use to log in to your mail service (e.g., GMail). to is a String array that holds all of the email addresses that you want to send the message to.

    String host = "smtp.gmail.com";
    String from = "username";
    String pass = "password";
    Properties props = System.getProperties();
    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 = {"[email protected]"}; // 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();
Bill the Lizard
+3  A: 

Even though this question is closed, I'd like to post a counter solution, but now using Vesijama (Open Source JavaMail smtp wrapper):

final Email email = new Email();

String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"[email protected]"};

email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
    email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");

new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);
A: 

This is what I do when i want to send email with attachment, work fine. :)

 public class NewClass {

    public static void main(String[] args) {
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); // smtp port
            Authenticator auth = new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username-gmail", "password-gmail");
                }
            };
            Session session = Session.getDefaultInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("[email protected]"));
            msg.setSubject("Try attachment gmail");
            msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
            //add atleast simple body
            MimeBodyPart body = new MimeBodyPart();
            body.setText("Try attachment");
            //do attachment
            MimeBodyPart attachMent = new MimeBodyPart();
            FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
            attachMent.setDataHandler(new DataHandler(dataSource));
            attachMent.setFileName("file-sent.txt");
            attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(body);
            multipart.addBodyPart(attachMent);
            msg.setContent(multipart);
            Transport.send(msg);
        } catch (AddressException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
Ifnu
+3  A: 

Other people have good answers above, but I wanted to add a note on my experience here. I've found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access. The emails I was sending were not spam, but were website "welcome" emails when users registered with my system. So, YMMV, and I wouldn't rely on Gmail for a production webapp. If you're sending email on a user's behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.

Also, if you're using Spring, here's a working config to use Gmail for outbound SMTP:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="465"/>
    <property name="username" value="${mail.username}"/>
    <property name="password" value="${mail.password}"/>
    <property name="javaMailProperties">
        <value>
            mail.debug=true
            mail.smtp.auth=true
            mail.smtp.socketFactory.class=java.net.SocketFactory
            mail.smtp.socketFactory.fallback=false
        </value>
    </property>
</bean>
Jason Thrasher
Thanks Jason, for the configuration settings example and for the warning about outbound mail limits. I've never run into the limit before, but I'm sure other people will find that information useful.
Bill the Lizard
I'd like to know more about that spam limit... I do have to send several emails, should I split them in groups? wait for a specified amount of time? Anybody knows the details of google mails limitations?
opensas
A: 

while running this code i am getting the exception Feb 3, 2009 11:47:35 AM com.addsoft.struts.NewClass main SEVERE: null javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.AuthenticationFailedException at javax.mail.Transport.send0(Transport.java:218) at javax.mail.Transport.send(Transport.java:80) at com.addsoft.struts.NewClass.main(NewClass.java:74)

can you please help me!!

Ashim Ghosh
A: 
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail
{
         String  d_email = "[email protected]",
            d_password = "****",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Testing",
            m_text = "Hey, this is the testing email using smtp.gmail.com.";
    public static void main(String[] args)
    {
                String[] to={"[email protected]"};
                String[] cc={"[email protected]"};
                String[] bcc={"[email protected]"};
                //This is for google
                        Mail.sendMail("[email protected]","password","smtp.gmail.com","465","true",
"true",true,"javax.net.ssl.SSLSocketFactory","false",to,cc,bcc,
"hi baba don't send virus mails..","This is my style...of reply..
If u send virus mails..");             
    }

        public synchronized static boolean sendMail(String userName,String passWord,String host,String port,String starttls,String auth,boolean debug,String socketFactoryClass,String fallback,String[] to,String[] cc,String[] bcc,String subject,String text){
                Properties props = new Properties();
                //Properties props=System.getProperties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
                if(!"".equals(port))
        props.put("mail.smtp.port", port);
                if(!"".equals(starttls))
        props.put("mail.smtp.starttls.enable",starttls);
        props.put("mail.smtp.auth", auth);
                if(debug){
                props.put("mail.smtp.debug", "true");
                }else{
                props.put("mail.smtp.debug", "false");         
                }
                if(!"".equals(port))
        props.put("mail.smtp.socketFactory.port", port);
                if(!"".equals(socketFactoryClass))
        props.put("mail.smtp.socketFactory.class",socketFactoryClass);
                if(!"".equals(fallback))
        props.put("mail.smtp.socketFactory.fallback", fallback);

        try
        {
                        Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress("[email protected]"));
                        for(int i=0;i<to.length;i++){
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
                        }
                        for(int i=0;i<cc.length;i++){
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
                        }
                        for(int i=0;i<bcc.length;i++){
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
                        }
            msg.saveChanges();
                        Transport transport = session.getTransport("smtp");
                        transport.connect(host, userName, passWord);
                        transport.sendMessage(msg, msg.getAllRecipients());
                        transport.close();
                        return true;
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
                        return false;
        }
        }

}
vishnu