【20210521更新】Windows 10 21H1/Server 2019/Office 2019下载

夜鹰 2019-10-22 12:16:03
加精

特别说明:本帖不提供任何密钥或激活方法,请大家也不要在帖内回复或讨论涉及版权的相关内容,仅提供原版ISO下载链接


欢迎加入QQ讨论群:20967576

20210521更新说明
更新21H1版本2021年5月最新正式版本19043.985
增加Windows Server 2019下载

20201014更新说明
更新2004版本2020年9月最新正式版本19041.508
20200515更新说明
更新2004版本2020年4月最新正式版本19041.264
20200506更新说明
更新1909版本2020年1月最新正式版本18363.815(移至本帖62楼)
20200114更新说明
更新1909版本2019年12月最新正式版本18363.535
20190523更新说明
更新1903版本2019年5月最新正式版本18362.116(移至本帖62楼)

由于论坛限制,以下更新请访问旧帖
https://bbs.csdn.net/topics/391111024
20190409更新说明
更新1809版本2019年3月正式版本17763.379
20190222更新说明
更新1809版本2019年1月正式版本17763.316;新增Visio 2019和Project 2019下载
20181205更新说明
新增1809各正式版本下载
20181114更新说明
增加官方1809版本升级渠道及工具
20181023更新说明
新增Office 2019、OneNote 2016下载,Office 2016等资源移至本帖177楼
20180507更新说明:
Windows 10更新至1803(17134)版本
20180314更新说明:
Windows 10更新至1709(16299)版本
20171130更新说明:
新增下载(移至旧帖177楼):
1.Office Home and Business 2016 for Mac
2.OneNote 2013 中文版
3.Visio 2016 英文版
4.Project 2016英文版


推荐购买正版Windows 10:
https://www.microsoftstore.com.cn/software/windows


下载指引:

21H1(19043.985)版本 (20210521更新) 1楼
2004(19041.508)版本(20201014更新) 62楼
1909(18363.815)版本 (20200506更新) 62楼

由于论坛限制,以下更新请访问旧帖
https://bbs.csdn.net/topics/391111024
1809(17763)版本 (20190409更新)318楼
1803(17134)版本 (20180507更新) 204楼
1709(16299)版本 (20180314更新) 133楼
1703(15063)版本 (20170630更新) 115楼
1607(14393)版本 (20160803更新) 97楼
1511(10586)版本 (20151112更新) 68楼
10240版本 (20150729更新) 68楼




系统要求

升级安装
如果要在普通电脑或平板电脑上升级到 Windows 10,必须满足下文所述的要求。最新版本的操作系统:确保您运行的是最新版本,即 Windows 7 SP1 或 Windows 8.1 更新。

全新安装*
处理器:1 GHz 或更快的处理器或 SoC
RAM:1 GB(32 位)或 2 GB(64 位)
硬盘空间:16 GB(32 位操作系统)或 20 GB(64 位操作系统)
图形卡:DirectX 9 或更高版本(包含 WDDM 1.0 驱动程序)
显示器:800x600

*以上为微软官方给出的最低要求(详见后面前述1中链接)

一、前述

1、下载前请详细阅读《查找 Windows 10 电脑规格和系统需求》:
https://www.microsoft.com/zh-cn/windows/windows-10-specifications#system-specifications
2、Windows 10 一共有四个版本:家庭版(Home)/专业版(Professional)/企业版(Enterprise)/教育版(Education)。其中企业版和教育版的功能几乎是一致的。
3、版本比较*:

*官方最新版本比较列表:
https://www.microsoft.com/zh-cn/windowsforbusiness/compare

二、下载(请直接复制地址到下载工具)

通过“微软 Windows 10 易升”工具升级
https://www.microsoft.com/zh-cn/software-download/windows10


20H1(19043.985)版本(20210521更新)

Windows 10 (business edition), version 21H1 (x64) - DVD (Chinese-Simplified)

文件:cn_windows_10_business_editions_version_21h1_x64_dvd_57455ea1.iso
大小:5.3GB
MD5:E2B67B11553F15802E4708A786A715BD
SHA1:D35C56C76F9C5D0F03CAB06926035BB9536B7A25
SHA256:F1FA599DA150F0443BF4ED01895AA5B1F447855934B12A0D750A74A69DC263D7

ed2k://|file|cn_windows_10_business_editions_version_21h1_x64_dvd_57455ea1.iso|5693655040|68EB323345DC095D367A19CB3A22342C|/



Windows 10 (consumer edition), version 21H1 (x64) - DVD (Chinese-Simplified)

文件:cn_windows_10_consumer_editions_version_21h1_x64_dvd_1baf479d.iso
大小:5.41GB
MD5:060A010410E46B58A92960ACBF3B3C1A
SHA1:667836E090DBA6B2CDD593152F8E51D497F5779D
SHA256:DF88FFFE7E4763A7A01CF2F6546C83A864DA3E4DA35C78EC0838E2339371DB8F

ed2k://|file|cn_windows_10_consumer_editions_version_21h1_x64_dvd_1baf479d.iso|5807677440|E53960C7CAD323F60442A8AB9C269C2E|/

================

Windows Server 2019 (Updated July 2020) (x64) - DVD (Chinese-Simplified)

文件:cn_windows_server_2019_updated_july_2020_x64_dvd_2c9b67da.iso
大小:5.29GB
MD5:B5F339DC7743D202FEF3E0E0763D6B0C
SHA1:A2021F99E0B49D4AF5C5B83A8BC6B8A664AD1BC0
SHA256:041EED795E6452503D49136AF14EF65A87BFAFB8293FCFE5A63B9A45126411D6

ed2k://|file|cn_windows_server_2019_updated_july_2020_x64_dvd_2c9b67da.iso|5675251712|19AE348F0D321785007D95B7D2FAF320|/



一楼持续更新中,敬请等待......
由于帖子字数限制,其它版本请到相应楼层查看

==========================================================

三、版本的选择

1、Business editions和Consumer editions是微软两种不同的授权方式,分别相当于原来的批量授权版和零售版,根据需要选择即可。
2、通过官方网站升级
https://www.microsoft.com/zh-cn/software-download/windows10
注意:在线升级前务必保存重要资料!

四、其他信息
1.Windows 10 版本信息:
https://docs.microsoft.com/zh-cn/windows/release-information/

2.Windows 即服务概述:
https://docs.microsoft.com/zh-cn/windows/deployment/update/waas-overview

3.用于更新和升级的 Windows 10 服务选项
https://docs.microsoft.com/zh-cn/previous-versions//mt598226(v=vs.85)?redirectedfrom=MSDN#%E4%B8%AD%E5%9B%BD%EF%BC%88%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87%EF%BC%89

4.Windows 10更多相关信息
https://docs.microsoft.com/zh-cn/previous-versions//dn986868(v=vs.85)?redirectedfrom=MSDN

============================================================



推荐购买正版Office 2019或Office 365:
https://www.microsoftstore.com.cn/software/office


Microsoft Office 2019

20181007更新:Office Professional Plus 2019 (x86 and x64) 简体中文版
ed2k://|file|cn_office_professional_plus_2019_x86_x64_dvd_5e5be643.iso|3775004672|1E4FFA5240F21F60DC027F73F1C62FF4|/
文件名
cn_office_professional_plus_2019_x86_x64_dvd_5e5be643.iso
SHA1
d850365b23e1e1294112a51105a2892b2bd88eb9
文件大小
3.52GB
发布时间
2018-10-03

20181023更新:OneNote 2016 (x86 and x64) 简体中文版

https://support.office.com/zh-cn/article/%E5%AE%89%E8%A3%85%E6%88%96%E9%87%8D%E6%96%B0-onenote-2016-for-windows-c08068d8-b517-4464-9ff2-132cb9c45c08?omkt=zh-CN&ui=zh-CN&rs=zh-CN&ad=CN

Visio 2019

Visio Professional 2019 (x86 and x64) – DVD (Chinese-Simplified)
文件名:cn_visio_professional_2019_x86_x64_dvd_97bda48c.iso
SHA1:c82c7d1967870307afbff0d4ef4e9e59219ad857
文件大小:3.52 GB
发布时间:2018-10-03
ed2k://%7Cfile%7Ccn_visio_professional_2019_x86_x64_dvd_97bda48c.iso%7C3775004672%7C26D248309B18EDBEEBE8DC43C55995DB%7C/

Project 2019
Project Professional 2019 (x86 and x64) – DVD (Chinese-Simplified)
文件名:cn_project_professional_2019_x86_x64_dvd_cfa04e72.iso
SHA1:4e8605ebe917a7e4e4321d46e336d844e91ff8ba
文件大小:3.52 GB
发布时间:2018-10-03
ed2k://%7Cfile%7Ccn_project_professional_2019_x86_x64_dvd_cfa04e72.iso%7C3775004672%7C8616DFB9676104B11823BAE7E5EE9CC0%7C/

以下资源已移至【本帖177楼】
Office 2016、OneNote 2013、Visio 2016、Project 2016、Office Home and Business 2016 for Mac

欢迎加入QQ讨论群:20967576

再次特别说明:本帖不提供任何密钥或激活方法,以上所有信息均来自网络
...全文
377375 96 打赏 收藏 转发到动态 举报
写回复
用AI写文章
96 条回复
切换为时间正序
请发表友善的回复…
发表回复
zch508 2021-05-12
  • 打赏
  • 举报
回复
谢谢,收藏了 ,版主辛苦了
YDP1205 2021-04-28
  • 打赏
  • 举报
回复
谢谢,分享总结
pc195505717 2021-03-20
  • 打赏
  • 举报
回复
好东西啊 谢谢
qq_23103311 2021-03-06
  • 打赏
  • 举报
回复
不错谢谢分享总结了
深度说 2021-02-22
  • 打赏
  • 举报
回复
谢谢分享总结了。
jyxh03 2021-01-29
  • 打赏
  • 举报
回复
更新至最新了。出现问题,win10 不动它的时候自动重启!持续性使用没问题
我是一道光_ 2021-01-25
  • 打赏
  • 举报
回复
好人,好帖,好种子。
mypwjcy 2021-01-13
  • 打赏
  • 举报
回复
感谢分享,非常齐全,。
chenmik 2021-01-08
  • 打赏
  • 举报
回复
多谢分享,收藏备用!!!
「已注销」 2021-01-06
  • 打赏
  • 举报
回复
非常好的帖子,版主辛苦了
战神/calmness 2020-12-20
  • 打赏
  • 举报
回复
不错,挺有用的,不错
walkermenpaul 2020-12-17
  • 打赏
  • 举报
回复
安装包越来越大,功能越来越新
kingiiL 2020-12-09
  • 打赏
  • 举报
回复
支持,感谢分享
bjnothing 2020-11-12
  • 打赏
  • 举报
回复
谢谢,收藏了
zsboy125 2020-11-11
  • 打赏
  • 举报
回复
一楼最上面的是win10版本?2020?下面是office?新人不是很懂
夜鹰 2020-11-11
  • 打赏
  • 举报
回复
引用 87 楼 zsboy125 的回复:
一楼最上面的是win10版本?2020?下面是office?新人不是很懂
1楼描述的很清楚了,目前最新版本就是Windows 10 20H2和Office 2019
gammachang 2020-10-30
  • 打赏
  • 举报
回复
谢谢分享,收藏备用!
xwj 2020-10-19
  • 打赏
  • 举报
回复
谢谢提供!收藏备用
「已注销」 2020-10-11
  • 打赏
  • 举报
回复
谢谢分享总结.........
江南不下雨_ 2020-09-13
  • 打赏
  • 举报
回复
感谢楼主
加载更多回复(76)
Fundamentals of the JavaMail API Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Tutorial tips 2 2. Introducing the JavaMail API 3 3. Reviewing related protocols 4 4. Installing JavaMail 6 5. Reviewing the core classes 8 6. Using the JavaMail API 13 7. Searching with SearchTerm 21 8. Exercises 22 9. Wrapup 32 Fundamentals of the JavaMail API Page 1 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 1. Tutorial tips Should I take this tutorial? Looking to incorporate mail facilities into your platform-independent Java solutions? Look no further than the JavaMail API, which offers a protocol-independent model for working with IMAP, POP, SMTP, MIME, and all those other Internet-related messaging protocols. With the help of the JavaBeans Activation Framework (JAF), your applications can now be mail-enabled through the JavaMail API. Concepts After completing this module you will understand the: * Basics of the Internet mail protocols SMTP, POP3, IMAP, and MIME * Architecture of the JavaMail framework * Connections between the JavaMail API and the JavaBeans Activation Framework Objectives By the end of this module you will be able to: * Send and read mail using the JavaMail API * Deal with sending and receiving attachments * Work with HTML messages * Use search terms to search for messages Prerequisites Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard Edition (J2SE) 1.2.x or 1.3.x. A general familiarity with object-oriented programming concepts and the Java programming language is necessary. The Java language essentials tutorial can help. copyright 1996-2000 Magelang Institute dba jGuru Contact jGuru has been dedicated to promoting the growth of the Java technology community through evangelism, education, and software since 1995. You can find out more about their activities, including their huge collection of FAQs at jGuru.com . To send feedback to jGuru about this course, send mail to producer@jguru.com . Course author: Formerly with jGuru.com , John Zukowski does strategic Java consulting for JZ Ventures, Inc. His latest book is titled Java Collections from Apress . Fundamentals of the JavaMail API Page 2 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 2. Introducing the JavaMail API What is the JavaMail API? The JavaMail API is an optional package (standard extension) for reading, composing, and sending electronic messages. You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, pine, and Microsoft Outlook. The API's main purpose is not for transporting, delivering, and forwarding messages; this is the purview of applications such as sendmail and other Mail Transfer Agent (MTA) type programs. MUA-type programs let users read and write e-mail, whereas MUAs rely on MTAs to handle the actual delivery. The JavaMail API is designed to provide protocol-independent access for sending and receiving messages by dividing the API into two parts: * The first part of the API is the focus of this course --basically, how to send and receive messages independent of the provider/protocol. * The second part speaks the protocol-specific languages, like SMTP, POP, IMAP, and NNTP. With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a sufficient set for free. Fundamentals of the JavaMail API Page 3 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 3. Reviewing related protocols Introduction Before looking into the JavaMail API specifics, let's step back and take a look at the protocols used with the API. There are basically four that you'll come to know and love: * SMTP * POP * IMAP * MIME You will also run across NNTP and some others. Understanding the basics of all the protocols will help you understand how to use the JavaMail API. While the API is designed to be protocol agnostic, you can't overcome the limitations of the underlying protocols. If a capability isn't supported by a chosen protocol, the JavaMail API doesn't magically add the capability on top of it. (As you'll soon see, this can be a problem when working with POP.) SMTP The Simple Mail Transfer Protocol (SMTP) is defined by RFC 821 . It defines the mechanism for delivery of e-mail. In the context of the JavaMail API, your JavaMail-based program will communicate with your company or Internet Service Provider's (ISP's) SMTP server. That SMTP server will relay the message on to the SMTP server of the recipient(s) to eventually be acquired by the user(s) through POP or IMAP. This does not require your SMTP server to be an open relay, as authentication is supported, but it is your responsibility to ensure the SMTP server is configured properly. There is nothing in the JavaMail API for tasks like configuring a server to relay messages or to add and remove e-mail accounts. POP POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. That is all it does, and that is also the source of a lot of confusion. Much of what people are familiar with when using POP, like the ability to see how many new mail messages they have, are not supported by POP at all. These capabilities are built into programs like Eudora or Microsoft Outlook, which remember things like the last mail received and calculate how many are new for you. So, when using the JavaMail API, if you want this type of information, you have to calculate it yourself. IMAP IMAP is a more advanced protocol for receiving messages. Defined in RFC 2060 , IMAP stands for Internet Message Access Protocol, and is currently in version 4, also known as IMAP4. When using IMAP, your mail server must support the protocol. You can't just change your program to use IMAP instead of POP and expect everything in IMAP to be supported. Assuming your mail server supports IMAP, your JavaMail-based program can take Fundamentals of the JavaMail API Page 4 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks advantage of users having multiple folders on the server and these folders can be shared by multiple users. Due to the more advanced capabilities, you might think IMAP would be used by everyone. It isn't. It places a much heavier burden on the mail server, requiring the server to receive the new messages, deliver them to users when requested, and maintain them in multiple folders for each user. While this does centralize backups, as users' long-term mail folders get larger and larger, everyone suffers when disk space is exhausted. With POP, saved messages get offloaded from the mail server. MIME MIME stands for Multipurpose Internet Mail Extensions. It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822 , RFC 2045 , RFC 2046 , and RFC 2047 . As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs. NNTP and others Because of the split of the JavaMail API between provider and everything else, you can easily add support for additional protocols. Sun maintains a list of third-party providers that take advantage of protocols for which Sun does not provide out-of-the-box support. You'll find support for NNTP (Network News Transport Protocol) [newsgroups], S/MIME (Secure Multipurpose Internet Mail Extensions), and more. Fundamentals of the JavaMail API Page 5 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 4. Installing JavaMail Introduction There are two versions of the JavaMail API commonly used today: 1.2 and 1.1.3. All the examples in this course will work with both. While 1.2 is the latest, 1.1.3 is the version included with the 1.2.1 version of the Java 2 Platform, Enterprise Edition (J2EE), so it is still commonly used. The version of the JavaMail API you want to use affects what you download and install. All will work with JDK 1.1.6+, Java 2 Platform, Standard Edition (J2SE) version 1.2.x, and J2SE version 1.3.x. Note: After installing Sun's JavaMail implementation, you can find many example programs in the demo directory. Installing JavaMail 1.2 To use the JavaMail 1.2 API, download the JavaMail 1.2 implementation, unbundle the javamail-1_2.zip file, and add the mail.jar file to your CLASSPATH. The 1.2 implementation comes with an SMTP, IMAP4, and POP3 provider besides the core classes. After installing JavaMail 1.2, install the JavaBeans Activation Framework. Installing JavaMail 1.1.3 To use the JavaMail 1.1.3 API, download the JavaMail 1.1.3 implementation, unbundle the javamail1_1_3.zip file, and add the mail.jar file to your CLASSPATH. The 1.1.3 implementation comes with an SMTP and IMAP4 provider, besides the core classes. If you want to access a POP server with JavaMail 1.1.3, download and install a POP3 provider. Sun has one available separate from the JavaMail implementation. After downloading and unbundling pop31_1_1.zip, add pop3.jar to your CLASSPATH, too. After installing JavaMail 1.1.3, install the JavaBeans Activation Framework. Installing the JavaBeans Activation Framework All versions of the JavaMail API require the JavaBeans Activation Framework. The framework adds support for typing arbitrary blocks of data and handling it accordingly. This doesn't sound like much, but it is your basic MIME-type support found in many browsers and mail tools today. After downloading the framework, unbundle the jaf1_0_1.zip file, and add the activation.jar file to your CLASSPATH. For JavaMail 1.2 users, you should now have added mail.jar and activation.jar to your CLASSPATH. For JavaMail 1.1.3 users, you should now have added mail.jar, pop3.jar, and activation.jar to your CLASSPATH. If you have no plans of using POP3, you don't Fundamentals of the JavaMail API Page 6 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks need to add pop3.jar to your CLASSPATH. If you don't want to change the CLASSPATH environment variable, copy the jar files to your lib/ext directory under the Java Runtime Environment (JRE) directory. For instance, for the J2SE 1.3 release, the default directory would be C:\jdk1.3\jre\lib\ext on a Windows platform. Using JavaMail with the Java 2 Enterprise Edition If you use J2EE, there is nothing special you have to do to use the basic JavaMail API; it comes with the J2EE classes. Just make sure the j2ee.jar file is in your CLASSPATH and you're all set. For J2EE 1.2.1, the POP3 provider comes separately, so download and follow the steps to include the POP3 provider as shown in the previous section "Installing JavaMail 1.1.3." J2EE 1.3 users get the POP3 provider with J2EE so do not require the separate installation. Neither installation requires you to install the JavaBeans Activation Framework. Exercise Exercise 1. How to set up a JavaMail environment on page 22 Fundamentals of the JavaMail API Page 7 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 5. Reviewing the core classes Introduction Before taking a how-to approach at looking at the JavaMail classes in depth, this section walks you through the core classes that make up the API: Session, Message, Address, Authenticator, Transport, Store, and Folder. All these classes are found in the top-level package for the JavaMail API, javax.mail, though you'll frequently find yourself using subclasses found in the javax.mail.internet package. Session The Session class defines a basic mail session. It is through this session that everything else works. The Session object takes advantage of a java.util.Properties object to get information like mail server, username, password, and other information that can be shared across your entire application. The constructors for the class are private. You can get a single default session that can be shared with the getDefaultInstance() method: Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); Or, you can create a unique session with getInstance(): Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); In both cases, the null argument is an Authenticator object that is not being used at this time. In most cases, it is sufficient to use the shared session, even if working with mail sessions for multiple user mailboxes. You can add the username and password combination in at a later step in the communication process, keeping everything separate. Message Once you have your Session object, it is time to move on to creating the message to send. This is done with a type of Message . Because Message is an abstract class, you must work with a subclass, in most cases javax.mail.internet.MimeMessage .A MimeMessage is an e-mail message that understands MIME types and headers, as defined in the different RFCs. Message headers are restricted to US-ASCII characters only, though non-ASCII characters can be encoded in certain header fields. To create a Message, pass along the Session object to the MimeMessage constructor: MimeMessage message = new MimeMessage(session); Fundamentals of the JavaMail API Page 8 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Note: There are other constructors, like for creating messages from RFC822-formatted input streams. Once you have your message, you can set its parts, as Message implements the Part interface (with MimeMessage implementing MimePart ). The basic mechanism to set the content is the setContent() method, with arguments for the content and the mime type: message.setContent("Hello", "text/plain"); If, however, you know you are working with a MimeMessage and your message is plain text, you can use its setText() method, which only requires the actual content, defaulting to the MIME type of text/plain: message.setText("Hello"); For plain text messages, the latter form is the preferred mechanism to set the content. For sending other kinds of messages, like HTML messages, use the former. For setting the subject, use the setSubject() method: message.setSubject("First"); Address Once you've created the Session and the Message, as well as filled the message with content, it is time to address your letter with an Address . Like Message, Address is an abstract class. You use the javax.mail.internet.InternetAddress class. To create an address with just the e-mail address, pass the e-mail address to the constructor: Address address = new InternetAddress("president@whitehouse.gov"); If you want a name to appear next to the e-mail address, you can pass that along to the constructor, too: Address address = new InternetAddress("president@whitehouse.gov", "George Bush"); You will need to create address objects for the message's from field as well as the to field. Unless your mail server prevents you, there is nothing stopping you from sending a message that appears to be from anyone. Once you've created the addresses, you connect them to a message in one of two ways. For identifying the sender, you use the setFrom() and setReplyTo() methods. message.setFrom(address) If your message needs to show multiple from addresses, use the addFrom() method: Fundamentals of the JavaMail API Page 9 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Address address[] = ...; message.addFrom(address); For identifying the message recipients, you use the addRecipient() method. This method requires a Message.RecipientType besides the address. message.addRecipient(type, address) The three predefined types of address are: * Message.RecipientType.TO * Message.RecipientType.CC * Message.RecipientType.BCC So, if the message was to go to the vice president, sending a carbon copy to the first lady, the following would be appropriate: Address toAddress = new InternetAddress("vice.president@whitehouse.gov"); Address ccAddress = new InternetAddress("first.lady@whitehouse.gov"); message.addRecipient(Message.RecipientType.TO, toAddress); message.addRecipient(Message.RecipientType.CC, ccAddress); The JavaMail API provides no mechanism to check for the validity of an e-mail address. While you can program in support to scan for valid characters (as defined by RFC 822) or verify the MX (mail exchange) record yourself, these are all beyond the scope of the JavaMail API. Authenticator Like the java.net classes, the JavaMail API can take advantage of an Authenticator to access protected resources via a username and password. For the JavaMail API, that resource is the mail server. The JavaMail Authenticator is found in the javax.mail package and is different from the java.net class of the same name. The two don't share the same Authenticator as the JavaMail API works with Java 1.1, which didn't have the java.net variety. To use the Authenticator, you subclass the abstract class and return a PasswordAuthentication instance from the getPasswordAuthentication() method. You must register the Authenticator with the session when created. Then, your Authenticator will be notified when authentication is necessary. You could pop up a window or read the username and password from a configuration file (though if not encrypted is not secure), returning them to the caller as a PasswordAuthentication object. Properties props = new Properties(); // fill props with any information Authenticator auth = new MyAuthenticator(); Session session = Session.getDefaultInstance(props, auth); Transport The final part of sending a message is to use the Transport class. This class speaks the Fundamentals of the JavaMail API Page 10 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks protocol-specific language for sending the message (usually SMTP). It's an abstract class and works something like Session. You can use the default version of the class by just calling the static send() method: Transport.send(message); Or, you can get a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); This latter way is best when you need to send multiple messages, as it will keep the connection with the mail server active between messages. The basic send() mechanism makes a separate connection to the server for each method call. Note: To watch the mail commands go by to the mail server, set the debug flag with session.setDebug(true). Store and folder Getting messages starts similarly to sending messages with a Session. However, after getting the session, you connect to a Store , quite possibly with a username and password or Authenticator. Like Transport, you tell the Store what protocol to use: // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); store.connect(host, username, password); After connecting to the Store, you can then get a Folder , which must be opened before you can read messages from it: Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); For POP3, the only folder available is the INBOX. If you are using IMAP, you can have other folders available. Note: Sun's providers are meant to be smart. While Message message[] = folder.getMessages(); might look like a slow operation reading every message from the server, only when you actually need to get a part of the message is the message content retrieved. Once you have a Message to read, you can get its content with getContent() or write its content to a stream with writeTo(). The getContent() method only gets the message content, while writeTo() output includes headers. Fundamentals of the JavaMail API Page 11 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks System.out.println(((MimeMessage)message).getContent()); Once you're done reading mail, close the connection to the folder and store. folder.close(aBoolean); store.close(); The boolean passed to the close() method of folder states whether or not to update the folder by removing deleted messages. Moving on Essentially, understanding how to use these seven classes is all you need for nearly everything with the JavaMail API. Most of the other capabilities of the JavaMail API build off these seven classes to do something a little different or in a particular way, like if the content is an attachment. Certain tasks, like searching, are isolated and are discussed later. Fundamentals of the JavaMail API Page 12 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 6. Using the JavaMail API Introduction You've seen how to work with the core parts of the JavaMail API. In the following sections you'll find a how-to approach for connecting the pieces to do specific tasks. Sending messages Sending an e-mail message involves getting a session, creating and filling a message, and sending it. You can specify your SMTP server by setting the mail.smtp.host property for the Properties object passed when getting the Session: String host = ...; String from = ...; String to = ...; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getDefaultInstance(props, null); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); message.setText("Welcome to JavaMail"); // Send message Transport.send(message); You should place the code in a try-catch block, as setting up the message and sending it can throw exceptions. Exercise: Exercise 2. How to send your first message on page 23 Fetching messages For reading mail, you get a session, get and connect to an appropriate store for your mailbox, open the appropriate folder, and get your messages. Also, don't forget to close the connection when done. String host = ...; String username = ...; String password = ...; // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); Fundamentals of the JavaMail API Page 13 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; iservers or providers. For instance, except for deleting messages, the POP protocol supports none of them. Checking for new mail is not a POP task but a task built into mail clients. To find out what flags are supported, ask the folder with getPermanentFlags(). To delete messages, you set the message's DELETED flag: message.setFlag(Flags.Flag.DELETED, true); Open up the folder in READ_WRITE mode first though: folder.open(Folder.READ_WRITE); Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages. folder.close(true); There is an expunge() method of Folder that can be used to delete the messages. However, it doesn't work for Sun's POP3 provider. Other providers may or may not implement the capabilities. It will more than likely be implemented for IMAP providers. Because POP only supports single access to the mailbox, you have to close the folder to delete the messages with Sun's provider. To unset a flag, just pass false to the setFlag() method. To see if a flag is set, check it with isSet(). Authenticating yourself You learned that you can use an Authenticator to prompt for username and password when needed, instead of passing them in as strings. Here you'll actually see how to more fully use authentication. Instead of connecting to the Store with the host, username, and password, you configure the Properties to have the host, and tell the Session about your custom Authenticator instance, as shown here: // Setup properties Properties props = System.getProperties(); props.put("mail.pop3.host", host); // Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getDefaultInstance(props, auth); // Get the store Store store = session.getStore("pop3"); store.connect(); You then subclass Authenticator and return a PasswordAuthentication object from the getPasswordAuthentication() method. The following is one such implementation, with a single field for both. (This isn't a Project Swing tutorial; just enter the two parts in the one field, separated by a comma.) Fundamentals of the JavaMail API Page 15 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks import javax.mail.*; import javax.swing.*; import java.util.*; public class PopupAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username, password; String result = JOptionPane.showInputDialog( "Enter 'username,password'"); StringTokenizer st = new StringTokenizer(result, ","); username = st.nextToken(); password = st.nextToken(); return new PasswordAuthentication(username, password); } } Because the PopupAuthenticator relies on Swing, it will start up the event-handling thread for AWT. This basically requires you to add a call to System.exit() in your code to stop the program. Replying to messages The Message class includes a reply() method to configure a new Message with the proper recipient and subject, adding "Re: " if not already there. This does not add any content to the message, only copying the from or reply-to header to the new recipient. The method takes a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true). MimeMessage reply = (MimeMessage)message.reply(false); reply.setFrom(new InternetAddress("president@whitehouse.gov")); reply.setText("Thanks"); Transport.send(reply); To configure the reply-to address when sending a message, use the setReplyTo() method. Exercise: Exercise 4. How to reply to mail on page 27 Forwarding messages Forwarding messages is a little more involved. There is no single method to call, and you build up the message to forward by working with the parts that make up a message. A mail message can be made up of multiple parts. Each part is a BodyPart , or more specifically, a MimeBodyPart when working with MIME messages. The different body parts get combined into a container called Multipart or, again, more specifically a MimeMultipart . To forward a message, you create one part for the text of your message and a second part with the message to forward, and combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. That's essentially it. To copy the content from one message to another, just copy over its Fundamentals of the JavaMail API Page 16 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks DataHandler , a class from the JavaBeans Activation Framework. // Create the message to forward Message forward = new MimeMessage(session); // Fill in header forward.setSubject("Fwd: " + message.getSubject()); forward.setFrom(new InternetAddress(from)); forward.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText( "Here you go with the original message:\n\n"); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(message.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message forward.setContent(multipart); // Send message Transport.send(forward); Working with attachments Attachments are resources associated with a mail message, usually kept outside of the message like a text file, spreadsheet, or image. As with common mail programs like Eudora and pine, you can attach resources to your mail message with the JavaMail API and get those attachments when you receive the message. Sending attachments: Sending attachments is quite like forwarding messages. You build up the parts to make the complete message. After the first part, your message text, you add other parts where the DataHandler for each is your attachment, instead of the shared handler in the case of a forwarded message. If you are reading the attachment from a file, your attachment data source is a FileDataSource . Reading from a URL, it is a URLDataSource . Once you have your DataSource, just pass it on to the DataHandler constructor, before finally attaching it to the BodyPart with setDataHandler(). Assuming you want to retain the original filename for the attachment, the last thing to do is to set the filename associated with the attachment with the setFileName() method of BodyPart. All this is shown here: // Define message Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail Attachment"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("Pardon Ideas"); Fundamentals of the JavaMail API Page 17 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send the message Transport.send(message); When including attachments with your messages, if your program is a servlet, your users must upload the attachment besides telling you where to send the message. Uploading each file can be handled with a form encoding type of multipart/form-data.
Note: Message size is limited by your SMTP server, not the JavaMail API. If you run into problems, consider increasing the Java heap size by setting the ms and mx parameters. Exercise: Exercise 5. How to send attachments on page 28 Getting attachments: Getting attachments out of your messages is a little more involved then sending them because MIME has no simple notion of attachments. The content of your message is a Multipart object when it has attachments. You then need to process each Part, to get the main content and the attachment(s). Parts marked with a disposition of Part.ATTACHMENT from part.getDisposition() are clearly attachments. However, attachments can also come across with no disposition (and a non-text MIME type) or a disposition of Part.INLINE. When the disposition is either Part.ATTACHMENT or Part.INLINE, you can save off the content for that message part. Just get the original filename with getFileName() and the input stream with getInputStream(). Multipart mp = (Multipart)message.getContent(); for (int i=0, n=multipart.getCount(); i"; message.setContent(htmlText, "text/html")); On the receiving end, if you fetch the message with the JavaMail API, there is nothing built into the API to display the message as HTML. The JavaMail API only sees it as a stream of bytes. To display the message as HTML, you must either use the Swing JEditorPane or some third-party HTML viewer component. if (message.getContentType().equals("text/html")) { String content = (String)message.getContent(); JFrame frame = new JFrame(); JEditorPane text = new JEditorPane("text/html", content); text.setEditable(false); JScrollPane pane = new JScrollPane(text); frame.getContentPane().add(pane); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.show(); } Including images with your messages: On the other hand, if you want your HTML content message to be complete, with embedded images included as part of the message, you must treat the image as an attachment and reference the image with a special cid URL, where the cid is a reference to the Content-ID header of the image attachment. The process of embedding an image is quite similar to attaching a file to a message, the only Fundamentals of the JavaMail API Page 19 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks difference is you have to tell the MimeMultipart that the parts are related by setting its subtype in the constructor (or with setSubType()) and set the Content-ID header for the image to a random string which is used as the src for the image in the img tag. The following demonstrates this completely. String file = ...; // Create the message Message message = new MimeMessage(session); // Fill its headers message.setSubject("Embedded Image"); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "

Hello

" + ""; messageBodyPart.setContent(htmlText, "text/html"); // Create a related multi-part to combine the parts MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); // Create part for the image messageBodyPart = new MimeBodyPart(); // Fetch the image and associate to part DataSource fds = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID","memememe"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message message.setContent(multipart); Exercise: Exercise 6. How to send HTML messages with images on page 29 Fundamentals of the JavaMail API Page 20 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 7. Searching with SearchTerm Introduction The JavaMail API includes a filtering mechanism found in the javax.mail.search package to build up a SearchTerm . Once built, you then ask a Folder what messages match, retrieving an array of Message objects: SearchTerm st = ...; Message[] msgs = folder.search(st); There are 22 different classes available to help you build a search term. * AND terms (class AndTerm) * OR terms (class OrTerm) * NOT terms (class NotTerm) * SENT DATE terms (class SentDateTerm) * CONTENT terms (class BodyTerm) * HEADER terms (FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..) Essentially, you build up a logical expression for matching messages, then search. For instance the following term searches for messages with a (partial) subject string of ADV or a from field of friend@public.com. You might consider periodically running this query and automatically deleting any messages returned. SearchTerm st = new OrTerm( new SubjectTerm("ADV:"), new FromStringTerm("friend@public.com")); Message[] msgs = folder.search(st); Fundamentals of the JavaMail API Page 21 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 8. Exercises About the exercises These exercises are designed to provide help according to your needs. For example, you might simply complete the exercise given the information and the task list in the exercise body; you might want a few hints; or you may want a step-by-step guide to successfully complete a particular exercise. You can use as much or as little help as you need per exercise. Moreover, because complete solutions are also provided, you can skip a few exercises and still be able to complete future exercises requiring the skipped ones. Each exercise has a list of any prerequisite exercises, a list of skeleton code for you to start with, links to necessary API pages, and a text description of the exercise goal. In addition, there is help for each task and a solutions page with links to files that comprise a solution to the exercise. Exercise 1. How to set up a JavaMail environment In this exercise you will install Sun's JavaMail reference implementation. After installing, you will be introduced to the demonstration programs that come with the reference implementation. Task 1: Download the latest version of the JavaMail API implementation from Sun. Task 2: Download the latest version of the JavaBeans Activation Framework from Sun. Task 3: Unzip the downloaded packages. You get a ZIP file for all platforms for both packages. Help for task 3: You can use the jar tool to unzip the packages. Task 4: Add the mail.jar file from the JavaMail 1.2 download and the activation.jar file from the JavaBeans Activation Framework download to your CLASSPATH. Help for task 4: Copy the files to your extension library directory. For Microsoft Windows, using the default installation copy, the command might look like the following: cd \javamail-1.2 copy mail.jar \jdk1.3\jre\lib\ext cd \jaf-1.0.1 copy activation.jar \jdk1.3\jre\lib\ext If you don't like copying the files to the extension library directory, detailed instructions are available from Sun for setting your CLASSPATH on Windows NT. Task 5: Go into the demo directory that comes with the JavaMail API implementation and compile the msgsend program to send a test message. Help for task 5: javac msgsend.java Fundamentals of the JavaMail API Page 22 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 6: Execute the program passing in a from address with the -o option, your SMTP server with the -M option, and the to address (with no option). You'll then enter the subject, the text of your message, and the end-of-file character (CTRL-Z) to signal the end of the message input. Help for task 6: Be sure to replace the from address, SMTP server, and to address. java msgsend -o from@address -M SMTP.Server to@address If you are not sure of your SMTP server, contact your system administrator or check with your Internet Service Provider. Task 7: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 1. How to set up a JavaMail environment: Solution Upon successful completion, the JavaMail reference implementation will be in your CLASSPATH. Exercise 2. How to send your first message In the last exercise you sent a mail message using the demonstration program provided with the JavaMail implementation. In this exercise, you'll create the program yourself. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton code: * MailExample.java Task 1: Starting with the skeleton code , get the system Properties. Help for task 1: Properties props = System.getProperties(); Task 2: Add the name of your SMTP server to the properties for the mail.smtp.host key. Fundamentals of the JavaMail API Page 23 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 2: props.put("mail.smtp.host", host); Task 3: Get a Session object based on the Properties. Help for task 3: Session session = Session.getDefaultInstance(props, null); Task 4: Create a MimeMessage from the session. Help for task 4: MimeMessage message = new MimeMessage(session); Task 5: Set the from field of the message. Help for task 5: message.setFrom(new InternetAddress(from)); Task 6: Set the to field of the message. Help for task 6: message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); Task 7: Set the subject of the message. Help for task 7: message.setSubject("Hello JavaMail"); Task 8: Set the content of the message. Help for task 8: message.setText("Welcome to JavaMail"); Task 9: Use a Transport to send the message. Help for task 9: Transport.send(message); Task 10: Compile and run the program, passing your SMTP server, from address, and to address on the command line. Fundamentals of the JavaMail API Page 24 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 10: java MailExample SMTP.Server from@address to@address Task 11: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 2. How to send your first message: Solution The following Java source file represents a solution to this exercise: * Solution/MailExample.java Exercise 3. How to check for mail In this exercise, create a program that displays the from address and subject for each message and prompts to display the message content. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton Code * GetMessageExample.java Task 1: Starting with the skeleton code , get or create a Properties object. Help for task 1: Properties props = new Properties(); Task 2: Get a Session object based on the Properties. Help for task 2: Session session = Session.getDefaultInstance(props, null); Task 3: Get a Store for your e-mail protocol, either pop3 or imap. Help for task 3: Store store = session.getStore("pop3"); Task 4: Connect to your mail host's store with the appropriate username and password. Fundamentals of the JavaMail API Page 25 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 4: store.connect(host, username, password); Task 5: Get the folder you want to read. More than likely, this will be the INBOX. Help for task 5: Folder folder = store.getFolder("INBOX"); Task 6: Open the folder read-only. Help for task 6: folder.open(Folder.READ_ONLY); Task 7: Get a directory of the messages in the folder. Save the message list in an array variable named message. Help for task 7: Message message[] = folder.getMessages(); Task 8: For each message, display the from field and the subject. Help for task 8: System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); Task 9: Display the message content when prompted. Help for task 9: System.out.println(message[i].getContent()); Task 10: Close the connection to the folder and store. Help for task 10: folder.close(false); store.close(); Task 11: Compile and run the program, passing your mail server, username, and password on the command line. Answer YES to the messages you want to read. Just hit ENTER if you don't. If you want to stop reading your mail before making your way through all the messages, enter QUIT. Help for task 11: java GetMessageExample POP.Server username password Fundamentals of the JavaMail API Page 26 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Exercise 3. How to check for mail: Solution The following Java source file represents a solution to this exercise. * Solution/GetMessageExample.java Exercise 4. How to reply to mail In this exercise, create a program that creates a canned reply message and attaches the original message if it's plain text. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 3. How to check for mail on page 25 Skeleton Code: * ReplyExample.java Task 1: The skeleton code already includes the code to get the list of messages from the folder and prompt you to create a reply. Task 2: When answered affirmatively, create a new MimeMessage from the original message. Help for task 2: MimeMessage reply = (MimeMessage)message[i].reply(false); Task 3: Set the from field to your e-mail address. Task 4: Create the text for the reply. Include a canned message to start. When the original message is plain text, add each line of the original message, prefix each line with the "> " characters. Help for task 4: To check for plain text messages, check the messages MIME type with mimeMessage.isMimeType("text/plain"). Task 5: Set the message's content, once the message content is fully determined. Task 6: Send the message. Task 7: Compile and run the program, passing your mail server, SMTP server, username, password, and from address on the command line. Answer YES to the messages you want to send replies. Just hit ENTER if you don't. If you want to stop going through your mail before Fundamentals of the JavaMail API Page 27 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks making your way through all the messages, enter QUIT. Help for task 7: java ReplyExample POP.Server SMTP.Server username password from@address Task 8: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 4. How to reply to mail: Solution The following Java source file represents a solution to this exercise. * Solution/ReplyExample.java Exercise 5. How to send attachments In this exercise, create a program that sends a message with an attachment. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 2. How to send your first message on page 23 Skeleton Code: * AttachExample.java Task 1: The skeleton code already includes the code to get the initial mail session. Task 2: From the session, get a Message and set its header fields: to, from, and subject. Task 3: Create a BodyPart for the main message content and fill its content with the text of the message. Help for task 3: BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Here's the file"); Task 4: Create a Multipart to combine the main content with the attachment. Add the main content to the multipart. Help for task 4: Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Fundamentals of the JavaMail API Page 28 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 5: Create a second BodyPart for the attachment. Task 6: Get the attachment as a DataSource. Help for task 6: DataSource source = new FileDataSource(filename); Task 7: Set the DataHandler for the message part to the data source. Carry the original filename along. Help for task 7: messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); Task 8: Add the second part of the message to the multipart. Task 9: Set the content of the message to the multipart. Help for task 9: message.setContent(multipart); Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the file as an attachment. Help for task 11: java AttachExample SMTP.Server from@address to@address filename Task 12: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 5. How to send attachments: Solution The following Java source file represents a solution to this exercise. * Solution/AttachExample.java Exercise 6. How to send HTML messages with images In this exercise, create a program that sends an HTML message with an image attachment where the image is displayed within the HTML message. Fundamentals of the JavaMail API Page 29 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 5. How to send attachments on page 28 Skeleton code: * logo.gif * HtmlImageExample.java Task 1: The skeleton code already includes the code to get the initial mail session, create the main message, and fill its headers (to, from, subject). Task 2: Create a BodyPart for the HTML message content. Task 3: Create a text string of the HTML content. Include a reference in the HTML to an image () that is local to the mail message. Help for task 3: Use a cid URL. The content-id will need to be specified for the image later. String htmlText = "

Hello

" + ""; Task 4: Set the content of the message part. Be sure to specify the MIME type is text/html. Help for task 4: messageBodyPart.setContent(htmlText, "text/html"); Task 5: Create a Multipart to combine the main content with the attachment. Be sure to specify that the parts are related. Add the main content to the multipart. Help for task 5: MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); Task 6: Create a second BodyPart for the attachment. Task 7: Get the attachment as a DataSource, and set the DataHandler for the message part to the data source. Task 8: Set the Content-ID header for the part to match the image reference specified in the HTML. Help for task 8: messageBodyPart.setHeader("Content-ID","memememe"); Task 9: Add the second part of the message to the multipart, and set the content of the Fundamentals of the JavaMail API Page 30 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks message to the multipart. Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the images as an inline image within the HTML text. Help for task 11: java HtmlImageExample SMTP.Server from@address to@address filename Task 12: Check if your mail reader recognizes the message as HTML and displays the image within the message, instead of as a link to an external attachment file. Help for task 12: If your mail reader can't display HTML messages, consider sending the message to a friend. Exercise 6. How to send HTML messages with images: Solution The following Java source files represent a solution to this exercise. * Solution/logo.gif * Solution/HtmlImageExample.java Fundamentals of the JavaMail API Page 31 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 9. Wrapup In summary The JavaMail API is a Java package used for reading, composing, and sending e-mail messages and their attachments. It lets you build standards-based e-mail clients that employ various Internet mail protocols, including SMTP, POP, IMAP, and MIME, as well as related protocols such as NNTP, S/MIME, and others. The API divides naturally into two parts. The first focuses on sending, receiving, and managing messages independent of the protocol used, whereas the second focuses on specific use of the protocols. The purpose of this tutorial was to show how to use the first part of the API, without attempting to deal with protocol providers. The core JavaMail API consists of seven classes --Session, Message, Address, Authenticator, Transport, Store, and Folder --all of which are found in javax.mail, the top-level package for the JavaMail API. We used these classes to work through a number of common e-mail-related tasks, including sending messages, retrieving messages, deleting messages, authenticating, replying to messages, forwarding messages, managing attachments, processing HTML-based messages, and searching or filtering mail lists. Finally, we provided a number of step-by-step exercises to help illustrate the concepts presented. Hopefully, this will help you add e-mail functionality to your platform-independent Java applications. Resources You can do much more with the JavaMail API than what's found here. The lessons and exercises found here can be supplemented by the following resources: * Download the JavaMail 1.2 API from the JavaMail API home page . * The JavaBeans Activation Framework is required for versions 1.2 and 1.1.3 of the JavaMail API. * The JavaMail-interest mailing list is a Sun-hosted discussion forum for developers. * Sun's JavaMail FAQ addresses the use of JavaMail in applets and servlets, as well as prototol-specific questions. * Tutorial author John Zukowski maintains jGuru's JavaMail FAQ . * Want to see how others are using JavaMail? Check out Sun's list of third-party products. * If you want more detail about JavaMail, read Rick Grehan's "How JavaMail keeps it simple" (Lotus Developer Network, June 2000). * Benoit Marchal shows how to use Java and XML to produce plain text and HTML newsletters in this two-part series, "Managing e-zines with JavaMail and XSLT" Part 1 (developerWorks, March 2001) and Part 2 (developerWorks, April 2001). * "Linking Applications with E-mail" (Lotus Developer Network, May 2000) discusses how groupware can facilitate communication, collaboration, and coordination among applications. Fundamentals of the JavaMail API Page 32 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Feedback Please let us know whether this tutorial was helpful to you and how we could make it better. We'd also like to hear about other tutorial topics you'd like to see covered. Thanks! For questions about the content of this tutorial, contact the author John Zukowski ( jaz@zukowski.net ) Colophon This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The Toot-O-Matic tool is a short Java program that uses XSLT stylesheets to convert the XML source into a number of HTML pages, a zip file, JPEG heading graphics, and PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML. Fundamentals of the JavaMail API Page 33
‘文本朗读.vbpType=ExeReference=*G{00020430-0000-0000-C000-000000000046}#2.0#0#C:WINDOWSSystem32stdole2.tlb#OLE AutomationReference=*G{C866CA3A-32F7-11D2-9602-00C04F8EE628}#5.0#0#C:Program FilesCommon FilesMicrosoft SharedSpeechsapi.dll#Microsoft Speech Object LibraryReference=*G{00020905-0000-0000-C000-000000000046}#8.3#0#C:Program FilesMicrosoft OfficeOFFICE11MSWORD.OLB#Microsoft Word 11.0 Object LibraryObject={3B7C8863-D78F-101B-B9B5-04021C009402}#1.2#0; richtx32.ocxObject={F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0; COMDLG32.OCXForm=文本朗读.frmForm=frmAbout.frmModule=mDeclares; MoudlesmDeclares.basModule=MSubclass; Moudlessubclass.basModule=MTimer; Moudles imer.basClass=cMemDC; ClassMoudlescMemDC.clsClass=cMenuBar; ClassMoudlescMenuBar.clsClass=cNCCalcSize; ClassMoudlescNCCalcSize.clsClass=cNeoCaption; ClassMoudlescNeoCaption.clsClass=cToolbarMenu; ClassMoudlescToolbarMenu.clsClass=INCAreaModifier; ClassMoudlesINCAreaModifier.clsClass=ISubclass; ClassMoudlesisubclass.clsClass=GSubclass; ClassMoudlessubclass.clsClass=CTimer; ClassMoudles imer.clsModule=Module1; Module1.basObject={6B7E6392-850A-101B-AFC0-4210102A8DA7}#1.3#0; COMCTL32.OCXIconForm="Form1"Startup="Form1"HelpFile=""Title="文本朗读"ExeName32="文本朗读.exe"Command32=""Name="工程1"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=1RevisionVer=22AutoIncrementVer=1ServerSupportFiles=0VersionCompanyName="安阳市监狱"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1DebugStartupOption=0[MS Transaction Server]AutoRefresh=1‘文本朗读.frmVERSION 5.00Object = "{3B7C8863-D78F-101B-B9B5-04021C009402}#1.2#0"; "richtx32.ocx"Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"Begin VB.Form Form1 AutoRedraw = -1 ‘True Caption = "文本播放器 1.1版" ClientHeight = 6255 ClientLeft = 165 ClientTop = 555 ClientWidth = 9855 Icon = "文本朗读.frx":0000 LinkTopic = "Form1" ScaleHeight = 6255 ScaleWidth = 9855 StartUpPosition = 2 ‘屏幕中心 Begin VB.HScrollBar HScroll2 Height = 255 Left = 1080 Max = 100 TabIndex = 14 Top = 5880 Value = 50 Width = 1815 End Begin VB.PictureBox PicCaption Height = 495 Left = 240 Picture = "文本朗读.frx":08CA ScaleHeight = 435 ScaleWidth = 8715 TabIndex = 11 Top = 3960 Visible = 0 ‘False Width = 8775 Begin VB.PictureBox PicBorder Height = 135 Left = 960 Picture = "文本朗读.frx":1710C ScaleHeight = 75 ScaleWidth = 915 TabIndex = 12 Top = 240 Visible = 0 ‘False Width = 975 End End Begin VB.CommandButton Command6 Caption = "继续朗读" Height = 390 Left = 150 TabIndex = 10 Top = 3480 Width = 2760 End Begin VB.CommandButton Command5 Caption = "暂停朗读" Height = 390 Left = 150 TabIndex = 9 Top = 3000 Width = 2760 End Begin VB.HScrollBar HScroll1 Height = 255 Left = 1080 Max = 100 TabIndex = 8 Top = 5400 Value = 100 Width = 1815 End Begin MSComDlg.CommonDialog CDg1 Left = 6840 Top = 4560 _ExtentX = 847 _ExtentY = 847 _Version = 393216 Filter = "文本文件(*.txt)|*.txt|所有文件|*.*" FilterIndex = 2 End Begin VB.OptionButton Option2 Caption = "朗读选定" Height = 315 Left = 1800 TabIndex = 6 Top = 4920 Width = 1230 End Begin VB.OptionButton Option1 Caption = "朗读全文" Height = 315 Left = 120 TabIndex = 5 Top = 4920 Width = 1230 End Begin VB.CommandButton Command4 Caption = "退出程序" Height = 390 Left = 150 TabIndex = 4 Top = 4440 Width = 2760 End Begin VB.CommandButton Command3 Caption = "结束朗读" Height = 390 Left = 150 TabIndex = 3 Top = 3960 Width = 2760 End Begin VB.CommandButton Command2 Caption = "开始朗读" Height = 390 Left = 150 TabIndex = 2 Top = 2520 Width = 2760 End Begin VB.CommandButton Command1 Caption = "打开文件" Height = 390 Left = 150 TabIndex = 1 Top = 2040 Width = 2760 End Begin RichTextLib.RichTextBox RTf1 Height = 6105 Left = 3120 TabIndex = 0 Top = 30 Width = 6615 _ExtentX = 11668 _ExtentY = 10769 _Version = 393217 BackColor = 15138775 HideSelection = 0 ‘False ScrollBars = 2 AutoVerbMenu = -1 ‘True TextRTF = $"文本朗读.frx":17996 End Begin VB.Label Label1 AutoSize = -1 ‘True Caption = "语速调节:" Height = 180 Index = 1 Left = 120 TabIndex = 13 Top = 5880 Width = 900 End Begin VB.Label Label1 AutoSize = -1 ‘True Caption = "音量调节:" Height = 180 Index = 0 Left = 120 TabIndex = 7 Top = 5400 Width = 900 End Begin VB.Image Image1 Height = 1935 Left = -15 Picture = "文本朗读.frx":17A33 Stretch = -1 ‘True Top = 30 Width = 3075 End Begin VB.Menu FILEMNU Caption = "文件(&F)" Begin VB.Menu OPENMNU Caption = "打开(&O)" End Begin VB.Menu LDMNU Caption = "朗读(&L)" End Begin VB.Menu FG Caption = "-" End Begin VB.Menu EXTMNU Caption = "退出(&X)" End End Begin VB.Menu HILMNU Caption = "帮助(&H)" Begin VB.Menu aboutmnu Caption = "关于…" End EndEndAttribute VB_Name = "Form1"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseDim ld As New SpeechLib.SpVoiceDim qorx As BooleanDim wb As StringPrivate m_cN As cNeoCaption‘这是我又一次对文本播放器进行修订,‘增加了打开word、rtf文本、音量调节功能‘但是如何保存文声音文件还没做到,对TTS的安装等还没搞清楚,‘今后还需进一步努力加以改进。yxf 2004年5月30日‘------------------------------------------------------------------‘增加语速控制功能 2004年6月28日Private Sub aboutmnu_Click()frmAbout.Show 1End SubPrivate Sub Command1_Click()On Error Resume NextRTf1.Text = ""Dim str As StringDim lstr$CDg1.ShowOpenIf CDg1.FileName <> "" ThenIf LCase(right(CDg1.FileName, 3)) = "rtf" ThenRTf1.LoadFile CDg1.FileName, 0ElseIf LCase(right(CDg1.FileName, 3)) = "doc" ThenForm1.Caption = "文本播放器1.1版--正在打开文件……"Dim myword As New Word.Applicationmyword.Documents.Open FileName:=CDg1.FileName myword.Selection.WholeStoryRTf1.Text = myword.Selectionmyword.Quit Set myword = NothingElseIf LCase(right(CDg1.FileName, 3)) = "txt" ThenForm1.Caption = "文本播放器1.1版--正在打开文件……"RTf1.LoadFile CDg1.FileName, rtfText‘opentxt CDg1.FileName, str, lstr‘RTf1 = lstrElse If MsgBox("文件无法识别,按文本格式打开?", vbYesNo, "提示") = 6 ThenForm1.Caption = "文本播放器1.1版--正在打开文件……"opentxt CDg1.FileName, str, lstrRTf1 = lstr Else Exit Sub End IfEnd IfEnd IfMe.Caption = "文本播放器1.1版--" + CDg1.FileNameEnd SubPrivate Sub Command2_Click()On Error Resume NextIf qorx Thenwb = RTf1.TextElsewb = RTf1.SelTextEnd IfSet ld = New SpeechLib.SpVoiceld.Volume = HScroll1ld.Rate = HScroll2 / 10ld.Speak wb, 1End SubPrivate Sub Command3_Click()ld.Speak "", 2Set ld = NothingEnd SubPrivate Sub Command4_Click()ld.Speak "", 2Set ld = NothingEndEnd SubPrivate Sub Command5_Click()On Error Resume Nextld.PauseEnd SubPrivate Sub Command6_Click()On Error Resume Nextld.ResumeEnd SubPrivate Sub EXTMNU_Click()Command4_ClickEnd SubPrivate Sub Form_Resize()If Form1.Width > 3300 And Me.Height > 5000 ThenForm1.RTf1.Width = Me.Width - 3300RTf1.Height = Me.Height - 1000ElseRTf1.Width = 5895End IfEnd SubPrivate Sub Skin(f As Form, cN As cNeoCaption) cN.ActiveCaptionColor = &HFFFFFF cN.InActiveCaptionColor = &HC0C0C0 cN.ActiveMenuColor = &H0& cN.ActiveMenuColorOver = &H0 cN.InActiveMenuColor = &H0& cN.MenuBackgroundColor = RGB(207, 203, 207) cN.CaptionFont.Name = "宋体" cN.CaptionFont.Size = 9 cN.MenuFont.Name = "宋体" cN.MenuFont.Size = 9 cN.Attach f, f.PicCaption.Picture, f.PicBorder.Picture, 19, 20, 90, 140, 240, 400 f.BackColor = RGB(207, 203, 207)End SubPrivate Sub Form_Load()‘Dim X0 As Long‘Dim Y0 As Long‘让窗体居中‘X0 = Screen.Width‘Y0 = Screen.Height‘X0 = (X0 - Me.Width) / 2‘Y0 = (Y0 - Me.Height) / 2‘Me.Move X0, Y0‘ Set m_cN = New cNeoCaption ‘ Skin Me, m_cNqorx = TrueRTf1.Text = " 文本播放器1.1版" + vbCrLf + " 河南省安阳市育才路" + vbCrLf + " 2004年5月8日"Option1.Value = TrueEnd SubPrivate Sub Form_Unload(Cancel As Integer)Command4.Value = TrueEnd SubPrivate Sub HScroll1_Change()On Error Resume Nextld.Volume = HScroll1End SubPrivate Sub HScroll2_Change()On Error Resume Nextld.Rate = HScroll2 / 10End SubPrivate Sub LDMNU_Click()Command2_ClickEnd SubPrivate Sub OPENMNU_Click()Command1_ClickEnd SubPrivate Sub Option2_Click()qorx = FalseEnd SubPrivate Sub Option1_Click()qorx = TrueEnd SubVERSION 5.00Begin VB.Form frmAbout BorderStyle = 3 ‘Fixed Dialog Caption = "关于 文本朗读器" ClientHeight = 3555 ClientLeft = 2340 ClientTop = 1935 ClientWidth = 5730 ClipControls = 0 ‘False Icon = "frmAbout.frx":0000 LinkTopic = "Form2" MaxButton = 0 ‘False MinButton = 0 ‘False ScaleHeight = 2453.724 ScaleMode = 0 ‘User ScaleWidth = 5380.766 ShowInTaskbar = 0 ‘False Begin VB.CommandButton cmdOK Cancel = -1 ‘True Caption = "确定" Default = -1 ‘True Height = 345 Left = 4125 TabIndex = 0 Top = 2625 Width = 1500 End Begin VB.CommandButton cmdSysInfo Caption = "系统信息(&S)..." Height = 345 Left = 4140 TabIndex = 1 Top = 3075 Width = 1485 End Begin VB.Label Label1 Caption = "作者:河南省安阳市监狱 yxf" Height = 255 Left = 240 TabIndex = 6 Top = 3240 Width = 3735 End Begin VB.Image Image1 BorderStyle = 1 ‘Fixed Single Height = 675 Left = 120 Picture = "frmAbout.frx":08CA Stretch = -1 ‘True Top = 240 Width = 720 End Begin VB.Line Line1 BorderColor = &H00808080& BorderStyle = 6 ‘Inside Solid Index = 1 X1 = 84.515 X2 = 5309.398 Y1 = 1687.583 Y2 = 1687.583 End Begin VB.Label lblDescription Caption = $"frmAbout.frx":175602 ForeColor = &H00000000& Height = 1170 Left = 1080 TabIndex = 2 Top = 1125 Width = 3765 End Begin VB.Label lblTitle Caption = "文本朗读器" BeginProperty Font Name = "隶书" Size = 21.75 Charset = 134 Weight = 400 Underline = -1 ‘True Italic = -1 ‘True Strikethrough = 0 ‘False EndProperty ForeColor = &H000000FF& Height = 600 Left = 1080 TabIndex = 4 Top = 120 Width = 3885 End Begin VB.Line Line1 BorderColor = &H00FFFFFF& BorderWidth = 2 Index = 0 X1 = 98.6 X2 = 5309.398 Y1 = 1697.936 Y2 = 1697.936 End Begin VB.Label lblVersion Caption = "版本:1.1" Height = 225 Left = 1050 TabIndex = 5 Top = 780 Width = 3885 End Begin VB.Label lblDisclaimer Caption = "警告:本软件可以自由使用,但因对其使用而 带来的任何不良后果概不负责!" ForeColor = &H00000000& Height = 420 Left = 255 TabIndex = 3 Top = 2625 Width = 3630 EndEndAttribute VB_Name = "frmAbout"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit‘ 注册表关键字安全选项...Const READ_CONTROL = &H20000Const KEY_QUERY_VALUE = &H1Const KEY_SET_VALUE = &H2Const KEY_CREATE_SUB_KEY = &H4Const KEY_ENUMERATE_SUB_KEYS = &H8Const KEY_NOTIFY = &H10Const KEY_CREATE_LINK = &H20Const KEY_ALL_ACCESS = KEY_QUERY_VALUE + KEY_SET_VALUE + _ KEY_CREATE_SUB_KEY + KEY_ENUMERATE_SUB_KEYS + _ KEY_NOTIFY + KEY_CREATE_LINK + READ_CONTROL ‘ 注册表关键字 ROOT 类型...Const HKEY_LOCAL_MACHINE = &H80000002Const ERROR_SUCCESS = 0Const REG_SZ = 1 ‘ 独立的空的终结字符串Const REG_DWORD = 4 ‘ 32位数字Const gREGKEYSYSINFOLOC = "SOFTWAREMicrosoftShared Tools Location"Const gREGVALSYSINFOLOC = "MSINFO"Const gREGKEYSYSINFO = "SOFTWAREMicrosoftShared ToolsMSINFO"Const gREGVALSYSINFO = "PATH"Private Declare Function RegOpenKeyEx Lib "advapi32" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, ByRef phkResult As Long) As LongPrivate Declare Function RegQueryValueEx Lib "advapi32" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, ByRef lpType As Long, ByVal lpData As String, ByRef lpcbData As Long) As LongPrivate Declare Function RegCloseKey Lib "advapi32" (ByVal hKey As Long) As LongPrivate Sub cmdSysInfo_Click() Call StartSysInfoEnd SubPrivate Sub cmdOK_Click() Unload MeEnd SubPrivate Sub Form_Load()Dim X0 As LongDim Y0 As Long‘让窗体居中X0 = Screen.WidthY0 = Screen.HeightX0 = (X0 - Me.Width) / 2Y0 = (Y0 - Me.Height) / 2Me.Move X0, Y0End SubPublic Sub StartSysInfo() On Error GoTo SysInfoErr Dim rc As Long Dim SysInfoPath As String ‘ 试图从注册表中获得系统信息程序的路径及名称... If GetKeyValue(HKEY_LOCAL_MACHINE, gREGKEYSYSINFO, gREGVALSYSINFO, SysInfoPath) Then ‘ 试图仅从注册表中获得系统信息程序的路径... ElseIf GetKeyValue(HKEY_LOCAL_MACHINE, gREGKEYSYSINFOLOC, gREGVALSYSINFOLOC, SysInfoPath) Then ‘ 已知32位文件版本的有效位置 If (Dir(SysInfoPath & "MSINFO32.EXE") <> "") Then SysInfoPath = SysInfoPath & "MSINFO32.EXE" ‘ 错误 - 文件不能被找到... Else GoTo SysInfoErr End If ‘ 错误 - 注册表相应条目不能被找到... Else GoTo SysInfoErr End If Call Shell(SysInfoPath, vbNormalFocus) Exit SubSysInfoErr: MsgBox "此时系统信息不可用", vbOKOnlyEnd SubPublic Function GetKeyValue(KeyRoot As Long, KeyName As String, SubKeyRef As String, ByRef KeyVal As String) As Boolean Dim i As Long ‘ 循环计数器 Dim rc As Long ‘ 返回代码 Dim hKey As Long ‘ 打开的注册表关键字句柄 Dim hDepth As Long ‘ Dim KeyValType As Long ‘ 注册表关键字数据类型 Dim tmpVal As String ‘ 注册表关键字值的临时存储器 Dim KeyValSize As Long ‘ 注册表关键自变量的尺寸 ‘------------------------------------------------------------ ‘ 打开 {HKEY_LOCAL_MACHINE...} 下的 RegKey ‘------------------------------------------------------------ rc = RegOpenKeyEx(KeyRoot, KeyName, 0, KEY_ALL_ACCESS, hKey) ‘ 打开注册表关键字 If (rc <> ERROR_SUCCESS) Then GoTo GetKeyError ‘ 处理错误... tmpVal = String$(1024, 0) ‘ 分配变量空间 KeyValSize = 1024 ‘ 标记变量尺寸 ‘------------------------------------------------------------ ‘ 检索注册表关键字的值... ‘------------------------------------------------------------ rc = RegQueryValueEx(hKey, SubKeyRef, 0, _ KeyValType, tmpVal, KeyValSize) ‘ 获得/创建关键字值 If (rc <> ERROR_SUCCESS) Then GoTo GetKeyError ‘ 处理错误 If (Asc(Mid(tmpVal, KeyValSize, 1)) = 0) Then ‘ Win95 外接程序空终结字符串... tmpVal = Left(tmpVal, KeyValSize - 1) ‘ Null 被找到,从字符串中分离出来 Else ‘ WinNT 没有空终结字符串... tmpVal = Left(tmpVal, KeyValSize) ‘ Null 没有被找到, 分离字符串 End If ‘------------------------------------------------------------ ‘ 决定转换的关键字的值类型... ‘------------------------------------------------------------ Select Case KeyValType ‘ 搜索数据类型... Case REG_SZ ‘ 字符串注册关键字数据类型 KeyVal = tmpVal ‘ 复制字符串的值 Case REG_DWORD ‘ 四字节的注册表关键字数据类型 For i = Len(tmpVal) To 1 Step -1 ‘ 将每位进行转换 KeyVal = KeyVal + Hex(Asc(Mid(tmpVal, i, 1))) ‘ 生成值字符。 By Char。 Next KeyVal = Format$("&h" + KeyVal) ‘ 转换四字节的字符为字符串 End Select GetKeyValue = True ‘ 返回成功 rc = RegCloseKey(hKey) ‘ 关闭注册表关键字 Exit Function ‘ 退出 GetKeyError: ‘ 错误发生后将其清除... KeyVal = "" ‘ 设置返回值到空字符串 GetKeyValue = False ‘ 返回失败 rc = RegCloseKey(hKey) ‘ 关闭注册表关键字End Function

1,508

社区成员

发帖
与我相关
我的任务
社区描述
Windows专区 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧