且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用java从pc发送短信到手机

更新时间:2022-11-26 16:27:37

请在此变量中进行一些修改



old:

  String smtphost =gmail.com; 

将其替换为

  String smtphost =smtp.gmail.com; 


I have built one application to send sms using java and i googled a lot and finally implemented the following code but i am getting many exceptions that i have given 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 = "mygmailuserid@gmail.com";
      String password = "mygmailpassword";
      String smtphost = "smtp.gmail.com";
      String compression = "My SMS Compression Information";
      String from = "mygmailid@gmail.com";
      String to = "+91mymobilenumber@sms.gmail.com";
      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();
}
} //

Program is running but in my mail box i found: Delivery to the following recipient failed permanently:

+91mymobilenumber@sms.gmail.com

How can i send sms using java?

It is urgently required as I have to show demo to my Project leader regarding how to send sms using java.

Any help is much appreciated

please make some modifications in this variable

old :

String smtphost = "gmail.com";

replace it to

String smtphost = "smtp.gmail.com";