您的位置:首页 > 编程语言 > Java开发

java 调用邮件接口发送邮件

2016-11-21 11:25 253 查看

一:pom配置 jar包

<dependency>

<groupId>javax.mail</groupId>

<artifactId>mail</artifactId>

<version>1.4.5</version>

</dependency>

二:需要发送邮件的端口,服务,邮件及账户和秘密

配置在mail.properties

email.host=mailsss

email.port=25

email.template.path=\\cn\\sss\\ssss\\mail\\temp

email.from=发送的邮件账户

username=名字

password=秘密

三:操作类

public class EmailHelper {

private static final ResourceBundle bundle = ResourceBundle.getBundle("mail");

private static final String sendFrom = bundle.getString("email.from");

private static final String username = bundle.getString("username");

private static final String password = bundle.getString("password");

private static final String host = bundle.getString("email.host");

public static void sendEmail(String someone, String subject, String content){

Properties props = new Properties();

props.setProperty("mail.host", host);

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

Authenticator authenticator = new Authenticator(){

@Override

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username,password);

}

};

Session session = Session.getDefaultInstance(props, authenticator);

session.setDebug(true);

Message message = new MimeMessage(session);

try {

message.setFrom(new InternetAddress(sendFrom));

message.setRecipients(RecipientType.TO,InternetAddress.parse(someone));

//message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开"));

try {

message.setSubject(subject);

message.setContent(content,"text/html;charset=UTF-8");

Transport.send(message);

} catch (Exception e) {

e.printStackTrace();

}

} catch (AddressException e) {

e.printStackTrace();

} catch (MessagingException e) {

e.printStackTrace();

}

}

}

四:测试方法

@Test

public void tsetemail(){

String content ="哈喽你好!";

EmailHelper.sendEmail("xiaoreqing@126.com", "提示", content);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  邮件发送