Sending SMS from a pc to a mobile using java

18,558

Solution 1

Please make some modifications to the following variable:

String smtphost = "gmail.com";

Replace it with:

String smtphost = "smtp.gmail.com";

Solution 2

Gmail does not provide a gateway for sending public SMS.

Sending SMS messages normally costs money.

Check this link out, it can prove to be helpful:

SMS JAVA Sample Code

Here is a link to another question asked on SO regarding the same issue:

i want to send sms to phone using java

Share:
18,558
sujit
Author by

sujit

Updated on June 04, 2022

Comments

  • sujit
    sujit almost 2 years

    I have built an application which sends SMS messages via Java, but I am getting many exceptions during the application execution (see below):

    package john;
    
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    
    public class SMTPSend {
    
        public SMTPSend() {
        }
    
        public void msgsend() {
          String username = "[email protected]";
          String password = "mygmailpassword";
          String smtphost = "smtp.gmail.com";
          String compression = "My SMS Compression Information";
          String from = "[email protected]";
          String to = "[email protected]";
          String body = "Hello SMS World!";
          Transport myTransport = null;
    
    try {
    Properties props = System.getProperties();
    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 mailSession = Session.getDefaultInstance(props, null);
    Message msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(compression);
    msg.setText(body);
    msg.setSentDate(new Date());
    
     myTransport = mailSession.getTransport("smtp");
      myTransport.connect(smtphost, username, password);
      msg.saveChanges();
      myTransport.sendMessage(msg, msg.getAllRecipients());
      myTransport.close();
     } catch (Exception e) {
        e.printStackTrace();
      }
    }
    
    public static void main(String[] argv) {
     SMTPSend smtpSend = new SMTPSend();
     smtpSend.msgsend();
    }
    } //
    

    The application is running but in my mail box I have received the following:

    Delivery to the following recipient failed permanently:
    
    [email protected]
    

    How can I send an SMS using Java code/libraries?