importjava.io.File;importjava.util.Date;importjava.util.Properties;importjavax.activation.DataHandler;importjavax.activation.FileDataSource;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;importjavax.mail.internet.MimeUtility;importjava.util.Properties;importjavax.mail.Address;importjavax.mail.Authenticator;importjavax.mail.Message;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;publicclassEmail{publicstaticvoidmain(String[]args){InternetAddress[]popAddressList=null;StringsmtpServer="smtp.qq.com";StringpopServer="pop.qq.com";StringSmtpAddress="2668208858@qq.com";StringPopAddresslist="545739504@qq.com";StringSubject="这是一封测试邮件";StringType="text/html";StringmessageText="邮件的内容:hello,world";String[]arrArchievList=newString[3];arrArchievList[0]="c:\\1.JPG";arrArchievList[1]="c:\\2.JPG";arrArchievList[2]="c:\\3.jpg";booleansessionDebug=false;try{java.util.Propertiesprops=System.getProperties();props.put("mail.smtp.host",smtpServer);//存储发送邮件服务器的信息props.put("mail.smtp.auth","false");//同时通过验证props.put("mail.transport.protocol","smtp");SessionmailSession=Session.getInstance(props);//根据属性新建一个邮件会话mailSession.setDebug(sessionDebug);Messagemsg=newMimeMessage(mailSession);//设定发件人的地址msg.setFrom(newInternetAddress(SmtpAddress));//设定收信人的地址popAddressList=InternetAddress.parse(PopAddresslist,false);msg.setRecipients(Message.RecipientType.TO,popAddressList);//设定信中的主题msg.setSubject(Subject);//设定送信的时间msg.setSentDate(newDate());//是否以附件方式发送邮件booleanbolSendByArchieve=false;//如果有附件,先将由件内容部分存起来if(arrArchievList!=null&&arrArchievList.length>0){//1.保存内容MimeMultipartmp=newMimeMultipart();MimeBodyPartmailContentPart=newMimeBodyPart();mailContentPart.setContent(messageText,Type+";charset=GBK");msg.setContent(messageText,Type+";charset=GBK");//这句很重要,千万不要忘了mp.setSubType("related");mp.addBodyPart(mailContentPart);//2.保存多个附件for(intindex=0;index{ Filefile=newFile(arrArchievList[index]);MimeBodyPartmailArchieve=newMimeBodyPart();FileDataSourcefds=newFileDataSource(arrArchievList[index]);mailArchieve.setDataHandler(newDataHandler(fds));mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"GBK","B"));mp.addBodyPart(mailArchieve);}//3.最后集成内容和附件,一起发送msg.setContent(mp);}else{msg.setContent(messageText,Type+";charset=GBK");}//发送邮件Transporttransport;msg.saveChanges();//存储邮件信息transport=mailSession.getTransport("smtp");//以smtp方式登录邮箱username填写你的发送邮件的用户名如bluewens,userpwd填写你的密码,如获88888888,即transport.connect("smtp.163.com","bluewens","88888888");transport.connect("smtp.qq.com","2668208858@qq.com");transport.sendMessage(msg,msg.getAllRecipients());//发送邮件,其中第二个参数是所有//已设好的收件人地址props.put("pop.qq.com","false");transport.close();System.out.println("邮件已发送成功!");}catch(Exceptionex){ex.printStackTrace();}}
相关分类