Jay
Jay

Reputation: 1265

How to send email from any user(Like gmail user, yahoomail user, etc) in java?

I done send mail to end user. But when i use gmail account at that time i have to change smtp.domain.com to smtp.gmail.com, same for if i send mail from yahoomail.com then i have to change smtp.gmail.com to smtp.mail.yahoo.com. So is there any solution in java for send mail from any domain user, means i want to make my code for universal. So any one have solution then please suggest to me. my code is below

enter code here

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("[email protected]", "123456");
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipient(Message.RecipientType.TO,
                     new InternetAddress("[email protected]"));
            message.setSubject("mail to user");
            message.setText("Hello world.....");

            Transport.send(message);
            System.out.println("Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Upvotes: 2

Views: 577

Answers (2)

SoumyaK
SoumyaK

Reputation: 11

Run this program from command Line....

>java SendMailSSL <Put desire mail server as argument eg smtp.domail.com>

And access this command line argument from your program....

 public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.host", args[0]);

Upvotes: 1

smk
smk

Reputation: 5912

Use the java Properties API. http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html Use the loadfromXML option to use a config file and make your properties configurable.

Alternatively you could pass a config file as a command line argument and make it configurable.

Or read from a database.

Many ways to solve this problem.

Upvotes: 1

Related Questions