Java发送邮件

		String to = "收件人邮箱";
		String host = "smtp.163.com";
		String name = "发件人邮箱";
		String pwd = "发件人邮箱密码";
		//获取系统属性
		Properties properties = System.getProperties();
		//设置邮箱服务器
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth", "true");
		try {
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);
			//获取Session对象
			Session session = Session.getDefaultInstance(properties, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(name, pwd);
				}
			});
			//创建MimeMessage对象
			MimeMessage message = new MimeMessage(session);
			//设置发件人
			message.setFrom(new InternetAddress(name));
			//设置收件人
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			//设置邮件主题
			message.setSubject("测试标题");
			//设置邮件内容
			message.setText("测试内容");
			//发送消息
			Transport.send(message);
			System.out.println("发送中...");
		} catch (MessagingException mex) {
			mex.printStackTrace();
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
message.setText()该方法用于写入文本,邮件内容可改为其它,如下:
注:替换"message.setText("测试内容");"代码实现
// 1.发送 HTML 消息, 可以插入html标签
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );

// 2.发送内容携带附件等
// 创建消息部分
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 消息
         messageBodyPart.setText("This is message body");
        
         // 创建多重消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 附件部分
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整消息
         message.setContent(multipart );

发表回复

您的电子邮箱地址不会被公开。

3 + 7 =