javamail邮件发送demo code

需要引用的javax.mail.*类,在javamail mailapi.jar中。

Properties props = System.getProperties();

props.setProperty("mail.smtp.host", "smtp.qq.com");

props.setProperty("mail.smtp.port", "25");

props.put("mail.smtp.auth", "true");



final String username = "[email protected]";

        final String password = "xxx";

        Session session = Session.getDefaultInstance(props,

                new Authenticator()  {

                    protected PasswordAuthentication getPasswordAuthentication() {

                        return new PasswordAuthentication(username, password);

                    }

                });



try {

            // -- Create a new message --

            Message msg = new MimeMessage(session);

            // -- Set the FROM and TO fields --

            msg.setFrom(new InternetAddress(username));

            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",false));

            msg.setSubject("邮件标题");

            

            MimeMultipart mp=new MimeMultipart();

            BodyPart bp = new MimeBodyPart();

            String html = "邮件内容<h1>Hello World</h1>";

            bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"   + html, "text/html;charset=UTF-8");

            mp.addBodyPart(bp);

            

            BodyPart bp1 = new MimeBodyPart();

            

            //附件

            FileDataSource fileds = new FileDataSource("C:/people.xml");

            bp1.setDataHandler(new DataHandler(fileds));

            bp1.setFileName(fileds.getName());

            mp.addBodyPart(bp1);

            

            msg.setSentDate(new Date());

            msg.setContent(mp);

            

            msg.saveChanges();

            Transport.send(msg);

            System.out.println("Message sent.");

        } catch (Exception e) {

            // TODO: handle exception

            e.printStackTrace();

        }

 

你可能感兴趣的:(javamail)