JAVA中发送电⼦邮件的⽅法
JAVA中发送邮件的⽅法不复杂,使⽤sun的JavaMail的架包就可以实现,也可以使⽤Spring Boot封装的⽅法,使⽤起来更加便捷。⼀、下载JavaMail的架包,并导⼊项⽬中,如下:
如果是maven项⽬,maven依赖如下:
1<dependency>
2<groupId>com.sun.mail</groupId>
3<artifactId>javax.mail</artifactId>
4<version>1.5.6</version>
5</dependency>
如果使⽤spring的⽅法,还需要导⼊以下maven依赖:
1<dependency>
2<groupId>org.springframework</groupId>
3<artifactId>spring-context-support</artifactId>
4<version>4.3.6.RELEASE</version>
5</dependency>
⼆、使⽤JavaMail发邮件的代码例⼦,如下:
1、在main函数中对各项参数进⾏赋值(参数说明已进⾏备注),即可通过send函数进⾏发送邮件操作。
1public class TestEmail {
2
3private final static String TIMEOUT_MS = "20000";
4
5public static void main(String[] args) {
6 String host = "ail.qq";
7 String user = "xxxxxx@qq";
8 String password = "xxxxxx";
9 String recipients = "xxxxxx@qq";
10 String cc = "";
11 String subject = "邮件发送测试";
三八妇女节祝福语简短20字12 String content = "邮件正⽂:<br>你好!";
13//⽅式1:通过URL获取附件
14// byte[] attachment = BytesByUrl("127.0.0.1/project/test.pdf");
15//⽅式2:通过本地路径获取附件
16byte[] attachment = BytesByFile("c://fujian.pdf");
17
18 String attachmentName = "";
重阳节的传说简短50字19try {
20 attachmentName = deWord("这是附件.pdf");
21 send(host, user, password, recipients, cc, subject, content, attachment, attachmentName);
22 } catch (Exception e) {
23 e.printStackTrace();
24 }
25 }
26
27/**
28 * @param host 邮件服务器主机名
29 * @param user ⽤户名
30 * @param password 密码
31 * @param recipients 收件⼈
32 * @param cc 抄送⼈
33 * @param subject 主题
34 * @param content 内容
35 * @param attachment 附件 [没有传 null]
36 * @param attachmentName 附件名称 [没有传 null]
37 * @throws Exception
38*/
39public static void send(final String host, final String user, final String password,
40final String recipients, final String cc, final String subject, final String content,
41final byte[] attachment,final String attachmentName) throws Exception {
42 Properties props = new Properties();
43 props.put("mail.smtp.host", host);
44 props.put("mail.smtp.auth", "true");
立春吃什么45 props.put("mail.smtp.timeout", TIMEOUT_MS);
46
47 Authenticator auth = new Authenticator() {
48 @Override
49protected PasswordAuthentication getPasswordAuthentication() {
50return new PasswordAuthentication(user, password);
51 }
52 };
53 Session session = Instance(props, auth);
54 MimeMessage msg = new MimeMessage(session);
55 msg.setFrom(new InternetAddress(user));
56 msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
57if (cc != null && cc.length() > 0) {
58 msg.setRecipients(Message.RecipientType.CC, cc);
59 }
60 msg.setSubject(subject);
61// 向multipart对象中添加邮件的各个部分内容,包括⽂本内容和附件
62 Multipart multipart = new MimeMultipart();
63// 添加邮件正⽂
64 BodyPart contentPart = new MimeBodyPart();
65 contentPart.setContent(content, "text/html;charset=UTF-8");
66 multipart.addBodyPart(contentPart);
67// 添加附件的内容
68if (attachment!=null) {
69 BodyPart attachmentBodyPart = new MimeBodyPart();
70 DataSource source = new ByteArrayDataSource(attachment,"application/octet-stream");
71 attachmentBodyPart.setDataHandler(new DataHandler(source));
72//deWord可以避免⽂件名乱码
73 attachmentBodyPart.deWord(attachmentName));
74 multipart.addBodyPart(attachmentBodyPart);
75 }
76// 将multipart对象放到message中
77 msg.setContent(multipart);
78// 保存邮件
79 msg.saveChanges();
80 Transport.send(msg, AllRecipients());
81 }
82 }
2、上⾯的例⼦中,如果有附件,可对附件进⾏设置。附件传参类型为byte数组,这⾥举2个例⼦,⽅式1通过⽹址获取byte数组,如下。⽅式2通过本地⽂件获取byte数组。具体可以查看另⼀篇⽂章:。
1public class FileUtil {
2
3public static byte[] getBytesByUrl(String urlStr) {
4try {
5 URL url = new URL(urlStr);
6 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
7 InputStream is = InputStream();
8 BufferedInputStream bis = new BufferedInputStream(is);
9 ByteArrayOutputStream baos = new ByteArrayOutputStream();又大又圆类似的词语
10final int BUFFER_SIZE = 2048;
11final int EOF = -1;
12int c;
13byte[] buf = new byte[BUFFER_SIZE];
14while (true) {
15 c = ad(buf);
16if (c == EOF)
17break;
18 baos.write(buf, 0, c);
19 }
20 conn.disconnect();
21 is.close();
22
23byte[] data = ByteArray();
24 baos.flush();
25return data;
26
27 } catch (Exception e) {
28 e.printStackTrace();
29 }
30return null;
31 }
32 }
2020-5-26 更新:
三、使⽤Spring Boot发邮件的代码例⼦,如下:
1public class MailUtil {
2
3private static JavaMailSenderImpl javaMailSender;
4
5private static final String SENDER = "xxxxxx@qq";
6
7static {
8 javaMailSender = new JavaMailSenderImpl();
9 javaMailSender.setHost("smtp.qq");// 链接服务器魔兽游戏名
10// javaMailSender.setPort(25);// 默认使⽤25端⼝发送
11 javaMailSender.setUsername("xxxxxx@qq");// 邮箱账号
12 javaMailSender.setPassword("xxxxxxxxxx");// 授权码
13 javaMailSender.setDefaultEncoding("UTF-8");
14// javaMailSender.setProtocol("smtp");
15
16// Properties properties = new Properties();
苏有朋马思纯17// properties.setProperty("mail.debug", "true");// 启⽤调试
18// properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
19// 设置通过ssl协议使⽤465端⼝发送、使⽤默认端⼝(25)时下⾯三⾏不需要
20// properties.setProperty("mail.smtp.auth", "true");// 开启认证
21// properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端⼝
22// properties.setProperty("mail.smtp.socketFactory.class", "javax.ssl.SSLSocketFactory");
23
24// javaMailSender.setJavaMailProperties(properties);
25 }
26
27public static void main(String[] args) throws Exception {
28 sendSimpleMail(new String[]{"xxxxxx@qq"}, "邮件主题", "邮件内容", false);
29 }
30
31/**
32 * 发送普通邮件
33 *
34 * @param to 收件⼈
35 * @param subject 主题
36 * @param text 正⽂
37 * @param isHtml 正⽂是否为html格式
38*/
39public static void sendSimpleMail(String[] to, String subject, String text, boolean isHtml) throws Exception {
40 MimeMessage message = ateMimeMessage();
41 MimeMessageHelper helper = new MimeMessageHelper(message, true);
42 helper.setFrom(SENDER, "通知");
43 helper.setTo(to);
44 helper.setSubject(subject);
45 helper.setText(text, isHtml);
46 javaMailSender.send(message);
47 }
48
49/**
50 * 发送带附件邮件
51 *
52 * @param to 收件⼈
53 * @param subject 主题
54 * @param text 正⽂
55 * @param files 附件
56*/
57public static void sendAttachmentMail(String[] to, String subject, String text, Map<String, File> files) throws Exception {
58 MimeMessage message = ateMimeMessage();
59 MimeMessageHelper helper = new MimeMessageHelper(message, true);
60 helper.setFrom(SENDER, "通知");
61 helper.setTo(to);
62 helper.setSubject(subject);
63 helper.setText(text);
64 Set<Map.Entry<String, File>> fileSet = Set();
65for (Map.Entry f : fileSet) {
66 helper.addAttachment((String) f.getKey(), (File) f.getValue());
67 }
68 javaMailSender.send(message);
69 }
70 }
注意12⾏的password不是你邮箱的登录密码,⽽是在邮箱中⽣成的授权码。获取授权码⽅法如下:
登录QQ邮箱→设置→账户→POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→开启“POP3/SMTP服务”,获取到⼀个授权码。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论