楼主: Lisrelchen
912 0

Sending Email Through a URLConnection using Java [推广有奖]

  • 0关注
  • 62粉丝

VIP

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
50057 个
通用积分
79.9387
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
Sending Email Through a URLConnection using Java

As mentioned earlier, Java includes support for different URL protocols through protocol handlers that are implemented internally to the Java SDK. These handlers include support for the mailto: protocol. Example 5-3 shows a program that uses a mailto: URL to send email. The program prompts the user to enter the sender, recipient or recipients, subject, and body of the message, and then creates an appropriatemailto: URL and obtains a URLConnection object for it. The program uses the setDoInput( ) and setDoOutput( ) methods to specify that it is writing data to the URLConnection. It obtains the appropriate stream with getOutputStream( ) and then writes the message headers and body to that stream, closing the stream when the message body is complete. The program uses the user.name system property and theInetAddress class to attempt to create a valid return address for the sender of the email, though this doesn’t actually work correctly on all platforms.

In order for the mailto: protocol handler to send mail, it must know what computer, or mailhost, to send it to. By default, it attempts to send it to the machine on which it is running. Some computers, particularly Unix machines on intranets, work as mailhosts, so this works fine. Other computers, such as PCs connected to the Internet by a dialup connection, have to specify a mailhost explicitly on the command line. For example, if your Internet service provider has the domain name isp.net, the appropriate mailhost is often mail.isp.net or smtp.isp.net. If you specify a mailhost, it is stored in the system property mail.host, which is read by the internal mailto: protocol handler.

Note that Example 5-3 uses the println( ) method to display messages to the console but uses the print( ) method and explicit “\r\n” line terminator characters to send text over the network. Different operating systems use different line terminators, and println( ) uses whatever terminator is expected on the local system. The standard line terminator for network services, however, is the two-character sequence “\r\n”. We use it explicitly here, so that this client program works correctly regardless of the platform-specific line terminator.

Example 5-3. SendMail.java

  1. Example 5-3. SendMail.java
  2. package je3.net;
  3. import java.io.*;
  4. import java.net.*;

  5. /**
  6. * This program sends e-mail using a mailto: URL
  7. **/
  8. public class SendMail {
  9.     public static void main(String[  ] args) {
  10.         try {
  11.             // If the user specified a mailhost, tell the system about it.
  12.             if (args.length >= 1)
  13.                 System.getProperties( ).put("mail.host", args[0]);
  14.             
  15.             // A Reader stream to read from the console
  16.             BufferedReader in =
  17.                 new BufferedReader(new InputStreamReader(System.in));
  18.             
  19.             // Ask the user for the from, to, and subject lines
  20.             System.out.print("From: ");
  21.             String from = in.readLine( );
  22.             System.out.print("To: ");
  23.             String to = in.readLine( );
  24.             System.out.print("Subject: ");
  25.             String subject = in.readLine( );
  26.             
  27.             // Establish a network connection for sending mail
  28.             URL u = new URL("mailto:" + to);      // Create a mailto: URL
  29.             URLConnection c = u.openConnection( ); // Create its URLConnection
  30.             c.setDoInput(false);                  // Specify no input from it
  31.             c.setDoOutput(true);                  // Specify we'll do output
  32.             System.out.println("Connecting...");  // Tell the user
  33.             System.out.flush( );                   // Tell them right now
  34.             c.connect( );                          // Connect to mail host
  35.             PrintWriter out =                     // Get output stream to host
  36.                 new PrintWriter(new OutputStreamWriter(c.getOutputStream( )));

  37.             // We're talking to the SMTP server now.
  38.             // Write out mail headers.  Don't let users fake the From address
  39.             out.print("From: \"" + from + "\" <" +
  40.                       System.getProperty("user.name") + "@" +
  41.                       InetAddress.getLocalHost( ).getHostName( ) + ">\r\n");
  42.             out.print("To: " + to + "\r\n");
  43.             out.print("Subject: " + subject + "\r\n");
  44.             out.print("\r\n");  // blank line to end the list of headers

  45.             // Now ask the user to enter the body of the message
  46.             System.out.println("Enter the message. " +
  47.                                "End with a '.' on a line by itself.");
  48.             // Read message line by line and send it out.
  49.             String line;
  50.             for(;;) {
  51.                 line = in.readLine( );
  52.                 if ((line == null) || line.equals(".")) break;
  53.                 out.print(line + "\r\n");
  54.             }
  55.             
  56.             // Close (and flush) the stream to terminate the message
  57.             out.close( );
  58.             // Tell the user it was successfully sent.
  59.             System.out.println("Message sent.");
  60.         }
  61.         catch (Exception e) {  // Handle any exceptions, print error message.
  62.             System.err.println(e);
  63.             System.err.println("Usage: java SendMail [<mailhost>]");
  64.         }
  65.     }
  66. }
复制代码


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:connection Connect Through ending Using Email different includes protocol message

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加JingGuanBbs
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-5-17 23:08