Java使用JavaMail发送邮件的方法
本文实例讲述了Java使用JavaMail发送邮件的方法。分享给大家供大家参考,具体如下:
代码一、Email_Autherticator.java服务器验证代码
importjavax.mail.Authenticator; importjavax.mail.PasswordAuthentication; publicclassEmail_AutherticatorextendsAuthenticator{ Stringusername="你邮箱的用户名"; Stringpassword="你邮箱的密码"; publicEmail_Autherticator(){ super(); } publicEmail_Autherticator(Stringuser,Stringpwd){ super(); username=user; password=pwd; } publicPasswordAuthenticationgetPasswordAuthentication(){ returnnewPasswordAuthentication(username,password); } }
代码二、Mail.java发送邮件的代码
importjava.util.Date; importjava.util.Properties; importjavax.mail.Address; importjavax.mail.Authenticator; importjavax.mail.Message; importjavax.mail.SendFailedException; importjavax.mail.Session; importjavax.mail.Transport; importjavax.mail.internet.InternetAddress; importjavax.mail.internet.MimeMessage; publicclassMail{ privateStringhost="smtp.126.com"; privateStringmail_head_name="thisisheadofthismail"; privateStringmail_head_value="thisisheadofthismail"; privateStringmail_to="254173774@qq.com"; privateStringmail_from="hackboyo@126.com"; privateStringmail_subject="thisisthesubjectofthistestmail"; privateStringmail_body="thisismail_bodyofthistestmail"; privateStringpersonalName="我的邮件"; publicvoidsendMail()throwsSendFailedException{ try{ Propertiesprops=newProperties();//获取系统环境 Authenticatorauth=newEmail_Autherticator();//进行邮件服务用户认证 props.put("mail.smtp.host",host); props.put("mail.smtp.auth","true"); System.out.println(props); Sessionsession=Session.getDefaultInstance(props,auth); //设置session,和邮件服务器进行通讯 MimeMessagemessage=newMimeMessage(session); message.setContent("Hello","text/plain");//设置邮件格式 message.setSubject(mail_subject);//设置邮件主题 message.setText(mail_body);//设置邮件内容 message.setHeader(mail_head_name,mail_head_value);//设置邮件标题 message.setSentDate(newDate());//设置邮件发送时期 Addressaddress=newInternetAddress(mail_from,personalName); message.setFrom(address);//设置邮件发送者的地址 Addresstoaddress=newInternetAddress(mail_to);//设置邮件接收者的地址 message.addRecipient(Message.RecipientType.TO,toaddress); System.out.println(message); Transport.send(message); System.out.println("SendMailOk!"); }catch(Exceptione){ e.printStackTrace(); } //returnflag; } }
代码三、Test.java测试发送邮件的代码
publicclassTest{ publicstaticvoidmain(String[]args){ Mailm=newMail(); try{ m.sendMail(); }catch(Exceptione){ } } }
希望本文所述对大家Java程序设计有所帮助。