使用java发送短信和邮件
(1)发送短信
1.1在中国网建SMS上注册一个用户名,并获取短信密钥(非登录密码)
1.2代码
import java.io.IOException; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; public class SendMessage { /** * @param args * @throws IOException * @throws HttpException */ public static void main(String[] args) throws HttpException, IOException { HttpClient client=new HttpClient(); PostMethod post=new PostMethod("http://gbk.sms.webchinese.cn"); //在头文件中设置转码 post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk"); NameValuePair[] data={ new NameValuePair("Uid","网建注册用户名"), new NameValuePair("Key","短信密钥"), new NameValuePair("smsMob","接收号码"), new NameValuePair("smsText","短信内容") }; post.setRequestBody(data); client.executeMethod(post); Header[] headers=post.getRequestHeaders(); int statusCode=post.getStatusCode(); System.out.println("statusCode:"+statusCode); for(Header h:headers){ System.out.println(h.toString()); } String result=new String(post.getResponseBodyAsString().getBytes("gbk")); System.out.println(result); post.releaseConnection(); }
1.3注意需要引入包:commons-logging-1.1.1.jar、commons-httpclient-3.1.jar、commons-codec-1.4.jar
1.4StatusCode说明:
短信发送后返回值 | 说 明 |
---|---|
-1 | 没有该用户账户 |
-2 | 接口密钥不正确 [查看密钥] 不是账户登陆密码 |
-21 | MD5接口密钥加密不正确 |
-3 | 短信数量不足 |
-11 | 该用户被禁用 |
-14 | 短信内容出现非法字符 |
-4 | 手机号格式不正确 |
-41 | 手机号码为空 |
-42 | 短信内容为空 |
-51 | 短信签名格式不正确 接口签名格式为:【签名内容】 |
-6 | IP限制 |
大于0 | 短信发送数量 |
2、发邮件
2.1smtp验证类
import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class SmtpAuthenticator extends Authenticator { String username=null; String password=null; public SmtpAuthenticator(String name,String password) { super(); this.username=name; this.password=password; } public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(this.username, this.password); } }
2.2发邮件的工具类
import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class JavaMailSendUtil { public void sendMail(String subject,String from,String[] to, String test,String[] filenames,String mineType){ try { Properties props=new Properties(); String smtp="smtp.163.com";//设置发送邮件所用到的smtp String servername="18862839372@163.com"; String serverpassword="************"; Session mailSession=null; MimeMessage mimeMsg=null; props=java.lang.System.getProperties(); props.put("mail.smtp.host", smtp);//设置SMTP主机 props.put("mail.smtp.auth", "true");//是否到服务器用户名和密码验证 //到服务器验证发送的用户名和密码是否正确 SmtpAuthenticator myEmailAuther=new SmtpAuthenticator(servername, serverpassword); //设置邮件会话 注意这里讲认证信息放进了Session的创建参数里 mailSession=javax.mail.Session.getInstance(props,(Authenticator)myEmailAuther); //设置传输协议 javax.mail.Transport transport=mailSession.getTransport("smtp"); //设置from、to等信息 mimeMsg=new javax.mail.internet.MimeMessage(mailSession); if(from!=null&&!from.equals("")){ InternetAddress sendFrom=new InternetAddress(from); mimeMsg.setFrom(sendFrom);//设置发送人地址 } InternetAddress[] sendTo=new InternetAddress[to.length]; for(int i=0;i<to.length;i++){ System.out.println("发送到:"+to[i]); sendTo[i]=new InternetAddress(to[i]); } mimeMsg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo); mimeMsg.setSubject(subject,"gb2312"); MimeBodyPart messageBodyPart1=new MimeBodyPart(); messageBodyPart1.setContent(test,mineType); //附件传输格式 Multipart multipart=new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); for(int i=0;i<filenames.length;i++){ MimeBodyPart messageBodyPart2=new MimeBodyPart(); String filename=filenames[i].split(";")[0]; System.out.println(filename); String displatname=filenames[i].split(";")[1]; //得到数据源 FileDataSource fds=new FileDataSource(filename); //BodyPart添加附件本身 messageBodyPart2.setDataHandler(new DataHandler(fds)); //BodyPart添加附件文件名 messageBodyPart2.setFileName(MimeUtility.encodeText(displatname)); multipart.addBodyPart(messageBodyPart2); } mimeMsg.setContent(multipart); //设置信件头的发送日期 mimeMsg.setSentDate(new Date()); mimeMsg.saveChanges(); //发送邮件 Transport.send(mimeMsg); transport.close(); System.out.println("消息发送成功"); } catch (Exception e) { // TODO: handle exception } } }
2.3测试类
public class TestMailSend { /** * @param args */ public static void main(String[] args) { String title="测试邮件"; String from="18862839372@163.com"; String sendTo[]={"1245226995@qq.com","jlsong186@126.com"}; String content="just test java send mail!!!!<br><a href=\"http://sjskt.javaeye.com\">My blog</a>"; String fileNames[]={"F:\\068.JPG;068.JPG"}; JavaMailSendUtil test=new JavaMailSendUtil(); try { test.sendMail(title, from, sendTo, content, fileNames, "text/html;charset=gb2312"); } catch (Exception e) { e.printStackTrace(); } } }