Commit | Line | Data |
68dc0745 |
1 | =head1 NAME |
2 | |
7678cced |
3 | perlfaq9 - Networking ($Revision: 1.19 $, $Date: 2005/01/21 12:14:12 $) |
68dc0745 |
4 | |
5 | =head1 DESCRIPTION |
6 | |
7 | This section deals with questions related to networking, the internet, |
8 | and a few on the web. |
9 | |
24f1ba9b |
10 | =head2 What is the correct form of response from a CGI script? |
68dc0745 |
11 | |
24f1ba9b |
12 | (Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...) |
13 | |
197aec24 |
14 | The Common Gateway Interface (CGI) specifies a software interface between |
15 | a program ("CGI script") and a web server (HTTPD). It is not specific |
16 | to Perl, and has its own FAQs and tutorials, and usenet group, |
17 | comp.infosystems.www.authoring.cgi |
24f1ba9b |
18 | |
1577cd80 |
19 | The original CGI specification is at: http://hoohoo.ncsa.uiuc.edu/cgi/ |
24f1ba9b |
20 | |
1577cd80 |
21 | Current best-practice RFC draft at: http://CGI-Spec.Golux.Com/ |
24f1ba9b |
22 | |
23 | Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html |
68dc0745 |
24 | |
197aec24 |
25 | These Perl FAQs very selectively cover some CGI issues. However, Perl |
24f1ba9b |
26 | programmers are strongly advised to use the CGI.pm module, to take care |
197aec24 |
27 | of the details for them. |
68dc0745 |
28 | |
24f1ba9b |
29 | The similarity between CGI response headers (defined in the CGI |
30 | specification) and HTTP response headers (defined in the HTTP |
31 | specification, RFC2616) is intentional, but can sometimes be confusing. |
68dc0745 |
32 | |
24f1ba9b |
33 | The CGI specification defines two kinds of script: the "Parsed Header" |
34 | script, and the "Non Parsed Header" (NPH) script. Check your server |
35 | documentation to see what it supports. "Parsed Header" scripts are |
36 | simpler in various respects. The CGI specification allows any of the |
37 | usual newline representations in the CGI response (it's the server's |
38 | job to create an accurate HTTP response based on it). So "\n" written in |
39 | text mode is technically correct, and recommended. NPH scripts are more |
40 | tricky: they must put out a complete and accurate set of HTTP |
41 | transaction response headers; the HTTP specification calls for records |
42 | to be terminated with carriage-return and line-feed, i.e ASCII \015\012 |
43 | written in binary mode. |
68dc0745 |
44 | |
24f1ba9b |
45 | Using CGI.pm gives excellent platform independence, including EBCDIC |
46 | systems. CGI.pm selects an appropriate newline representation |
47 | ($CGI::CRLF) and sets binmode as appropriate. |
c8db1d39 |
48 | |
24f1ba9b |
49 | =head2 My CGI script runs from the command line but not the browser. (500 Server Error) |
c8db1d39 |
50 | |
0bc0ad85 |
51 | Several things could be wrong. You can go through the "Troubleshooting |
52 | Perl CGI scripts" guide at |
53 | |
54 | http://www.perl.org/troubleshooting_CGI.html |
55 | |
197aec24 |
56 | If, after that, you can demonstrate that you've read the FAQs and that |
24f1ba9b |
57 | your problem isn't something simple that can be easily answered, you'll |
58 | probably receive a courteous and useful reply to your question if you |
59 | post it on comp.infosystems.www.authoring.cgi (if it's something to do |
60 | with HTTP or the CGI protocols). Questions that appear to be Perl |
61 | questions but are really CGI ones that are posted to comp.lang.perl.misc |
62 | are not so well received. |
c8db1d39 |
63 | |
197aec24 |
64 | The useful FAQs, related documents, and troubleshooting guides are |
24f1ba9b |
65 | listed in the CGI Meta FAQ: |
66 | |
67 | http://www.perl.org/CGI_MetaFAQ.html |
c8db1d39 |
68 | |
c8db1d39 |
69 | |
70 | =head2 How can I get better error messages from a CGI program? |
71 | |
72 | Use the CGI::Carp module. It replaces C<warn> and C<die>, plus the |
73 | normal Carp modules C<carp>, C<croak>, and C<confess> functions with |
74 | more verbose and safer versions. It still sends them to the normal |
75 | server error log. |
76 | |
77 | use CGI::Carp; |
78 | warn "This is a complaint"; |
79 | die "But this one is serious"; |
80 | |
81 | The following use of CGI::Carp also redirects errors to a file of your choice, |
82 | placed in a BEGIN block to catch compile-time warnings as well: |
83 | |
84 | BEGIN { |
85 | use CGI::Carp qw(carpout); |
86 | open(LOG, ">>/var/local/cgi-logs/mycgi-log") |
87 | or die "Unable to append to mycgi-log: $!\n"; |
88 | carpout(*LOG); |
89 | } |
90 | |
91 | You can even arrange for fatal errors to go back to the client browser, |
92 | which is nice for your own debugging, but might confuse the end user. |
93 | |
94 | use CGI::Carp qw(fatalsToBrowser); |
95 | die "Bad error here"; |
96 | |
97 | Even if the error happens before you get the HTTP header out, the module |
98 | will try to take care of this to avoid the dreaded server 500 errors. |
99 | Normal warnings still go out to the server error log (or wherever |
100 | you've sent them with C<carpout>) with the application name and date |
101 | stamp prepended. |
102 | |
68dc0745 |
103 | =head2 How do I remove HTML from a string? |
104 | |
f29c64d6 |
105 | The most correct way (albeit not the fastest) is to use HTML::Parser |
bed171df |
106 | from CPAN. Another mostly correct |
7d7e76cf |
107 | way is to use HTML::FormatText which not only removes HTML but also |
108 | attempts to do a little simple formatting of the resulting plain text. |
68dc0745 |
109 | |
110 | Many folks attempt a simple-minded regular expression approach, like |
c47ff5f1 |
111 | C<< s/<.*?>//g >>, but that fails in many cases because the tags |
68dc0745 |
112 | may continue over line breaks, they may contain quoted angle-brackets, |
a6dd486b |
113 | or HTML comment may be present. Plus, folks forget to convert |
114 | entities--like C<<> for example. |
68dc0745 |
115 | |
116 | Here's one "simple-minded" approach, that works for most files: |
117 | |
118 | #!/usr/bin/perl -p0777 |
119 | s/<(?:[^>'"]*|(['"]).*?\1)*>//gs |
120 | |
121 | If you want a more complete solution, see the 3-stage striphtml |
122 | program in |
a93751fa |
123 | http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz |
68dc0745 |
124 | . |
125 | |
c8db1d39 |
126 | Here are some tricky cases that you should think about when picking |
127 | a solution: |
128 | |
129 | <IMG SRC = "foo.gif" ALT = "A > B"> |
130 | |
d92eb7b0 |
131 | <IMG SRC = "foo.gif" |
c8db1d39 |
132 | ALT = "A > B"> |
133 | |
134 | <!-- <A comment> --> |
135 | |
136 | <script>if (a<b && a>c)</script> |
137 | |
138 | <# Just data #> |
139 | |
140 | <![INCLUDE CDATA [ >>>>>>>>>>>> ]]> |
141 | |
142 | If HTML comments include other tags, those solutions would also break |
143 | on text like this: |
144 | |
145 | <!-- This section commented out. |
146 | <B>You can't see me!</B> |
147 | --> |
148 | |
68dc0745 |
149 | =head2 How do I extract URLs? |
150 | |
e67d034e |
151 | You can easily extract all sorts of URLs from HTML with |
152 | C<HTML::SimpleLinkExtor> which handles anchors, images, objects, |
197aec24 |
153 | frames, and many other tags that can contain a URL. If you need |
154 | anything more complex, you can create your own subclass of |
155 | C<HTML::LinkExtor> or C<HTML::Parser>. You might even use |
e67d034e |
156 | C<HTML::SimpleLinkExtor> as an example for something specifically |
157 | suited to your needs. |
158 | |
49d635f9 |
159 | You can use URI::Find to extract URLs from an arbitrary text document. |
160 | |
197aec24 |
161 | Less complete solutions involving regular expressions can save |
e67d034e |
162 | you a lot of processing time if you know that the input is simple. One |
163 | solution from Tom Christiansen runs 100 times faster than most |
164 | module based approaches but only extracts URLs from anchors where the first |
197aec24 |
165 | attribute is HREF and there are no other attributes. |
e67d034e |
166 | |
167 | #!/usr/bin/perl -n00 |
168 | # qxurl - tchrist@perl.com |
169 | print "$2\n" while m{ |
170 | < \s* |
171 | A \s+ HREF \s* = \s* (["']) (.*?) \1 |
172 | \s* > |
173 | }gsix; |
174 | |
68dc0745 |
175 | |
176 | =head2 How do I download a file from the user's machine? How do I open a file on another machine? |
177 | |
49d635f9 |
178 | In this case, download means to use the file upload feature of HTML |
179 | forms. You allow the web surfer to specify a file to send to your web |
180 | server. To you it looks like a download, and to the user it looks |
181 | like an upload. No matter what you call it, you do it with what's |
182 | known as B<multipart/form-data> encoding. The CGI.pm module (which |
183 | comes with Perl as part of the Standard Library) supports this in the |
184 | start_multipart_form() method, which isn't the same as the startform() |
185 | method. |
186 | |
187 | See the section in the CGI.pm documentation on file uploads for code |
188 | examples and details. |
68dc0745 |
189 | |
190 | =head2 How do I make a pop-up menu in HTML? |
191 | |
c47ff5f1 |
192 | Use the B<< <SELECT> >> and B<< <OPTION> >> tags. The CGI.pm |
68dc0745 |
193 | module (available from CPAN) supports this widget, as well as many |
194 | others, including some that it cleverly synthesizes on its own. |
195 | |
196 | =head2 How do I fetch an HTML file? |
197 | |
46fc3d4c |
198 | One approach, if you have the lynx text-based HTML browser installed |
199 | on your system, is this: |
68dc0745 |
200 | |
201 | $html_code = `lynx -source $url`; |
202 | $text_data = `lynx -dump $url`; |
203 | |
d92eb7b0 |
204 | The libwww-perl (LWP) modules from CPAN provide a more powerful way |
205 | to do this. They don't require lynx, but like lynx, can still work |
206 | through proxies: |
46fc3d4c |
207 | |
c8db1d39 |
208 | # simplest version |
209 | use LWP::Simple; |
210 | $content = get($URL); |
211 | |
212 | # or print HTML from a URL |
46fc3d4c |
213 | use LWP::Simple; |
6cecdcac |
214 | getprint "http://www.linpro.no/lwp/"; |
46fc3d4c |
215 | |
c8db1d39 |
216 | # or print ASCII from HTML from a URL |
65acb1b1 |
217 | # also need HTML-Tree package from CPAN |
46fc3d4c |
218 | use LWP::Simple; |
f29c64d6 |
219 | use HTML::Parser; |
46fc3d4c |
220 | use HTML::FormatText; |
221 | my ($html, $ascii); |
222 | $html = get("http://www.perl.com/"); |
223 | defined $html |
224 | or die "Can't fetch HTML from http://www.perl.com/"; |
225 | $ascii = HTML::FormatText->new->format(parse_html($html)); |
226 | print $ascii; |
227 | |
c8db1d39 |
228 | =head2 How do I automate an HTML form submission? |
229 | |
7678cced |
230 | If you are doing something complex, such as moving through many pages |
231 | and forms or a web site, you can use C<WWW::Mechanize>. See its |
232 | documentation for all the details. |
233 | |
c8db1d39 |
234 | If you're submitting values using the GET method, create a URL and encode |
235 | the form using the C<query_form> method: |
236 | |
237 | use LWP::Simple; |
238 | use URI::URL; |
239 | |
240 | my $url = url('http://www.perl.com/cgi-bin/cpan_mod'); |
241 | $url->query_form(module => 'DB_File', readme => 1); |
242 | $content = get($url); |
243 | |
244 | If you're using the POST method, create your own user agent and encode |
245 | the content appropriately. |
246 | |
247 | use HTTP::Request::Common qw(POST); |
248 | use LWP::UserAgent; |
249 | |
250 | $ua = LWP::UserAgent->new(); |
251 | my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod', |
252 | [ module => 'DB_File', readme => 1 ]; |
253 | $content = $ua->request($req)->as_string; |
254 | |
255 | =head2 How do I decode or create those %-encodings on the web? |
68dc0745 |
256 | |
68dc0745 |
257 | |
575cc754 |
258 | If you are writing a CGI script, you should be using the CGI.pm module |
259 | that comes with perl, or some other equivalent module. The CGI module |
260 | automatically decodes queries for you, and provides an escape() |
261 | function to handle encoding. |
68dc0745 |
262 | |
575cc754 |
263 | |
264 | The best source of detailed information on URI encoding is RFC 2396. |
265 | Basically, the following substitutions do it: |
266 | |
48a4adce |
267 | s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode |
575cc754 |
268 | |
f05bbc40 |
269 | s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode |
575cc754 |
270 | |
271 | However, you should only apply them to individual URI components, not |
272 | the entire URI, otherwise you'll lose information and generally mess |
273 | things up. If that didn't explain it, don't worry. Just go read |
274 | section 2 of the RFC, it's probably the best explanation there is. |
275 | |
276 | RFC 2396 also contains a lot of other useful information, including a |
277 | regexp for breaking any arbitrary URI into components (Appendix B). |
68dc0745 |
278 | |
279 | =head2 How do I redirect to another page? |
280 | |
24f1ba9b |
281 | Specify the complete URL of the destination (even if it is on the same |
282 | server). This is one of the two different kinds of CGI "Location:" |
283 | responses which are defined in the CGI specification for a Parsed Headers |
284 | script. The other kind (an absolute URLpath) is resolved internally to |
285 | the server without any HTTP redirection. The CGI specifications do not |
286 | allow relative URLs in either case. |
287 | |
288 | Use of CGI.pm is strongly recommended. This example shows redirection |
289 | with a complete URL. This redirection is handled by the web browser. |
290 | |
291 | use CGI qw/:standard/; |
292 | |
a93751fa |
293 | my $url = 'http://www.cpan.org/'; |
24f1ba9b |
294 | print redirect($url); |
68dc0745 |
295 | |
68dc0745 |
296 | |
24f1ba9b |
297 | This example shows a redirection with an absolute URLpath. This |
298 | redirection is handled by the local web server. |
68dc0745 |
299 | |
24f1ba9b |
300 | my $url = '/CPAN/index.html'; |
301 | print redirect($url); |
c8db1d39 |
302 | |
d92eb7b0 |
303 | |
197aec24 |
304 | But if coded directly, it could be as follows (the final "\n" is |
24f1ba9b |
305 | shown separately, for clarity), using either a complete URL or |
197aec24 |
306 | an absolute URLpath. |
d92eb7b0 |
307 | |
24f1ba9b |
308 | print "Location: $url\n"; # CGI response header |
309 | print "\n"; # end of headers |
d92eb7b0 |
310 | |
c8db1d39 |
311 | |
68dc0745 |
312 | =head2 How do I put a password on my web pages? |
313 | |
49d635f9 |
314 | To enable authentication for your web server, you need to configure |
315 | your web server. The configuration is different for different sorts |
316 | of web servers---apache does it differently from iPlanet which does |
317 | it differently from IIS. Check your web server documentation for |
318 | the details for your particular server. |
68dc0745 |
319 | |
320 | =head2 How do I edit my .htpasswd and .htgroup files with Perl? |
321 | |
322 | The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a |
323 | consistent OO interface to these files, regardless of how they're |
426affbf |
324 | stored. Databases may be text, dbm, Berkeley DB or any database with |
325 | a DBI compatible driver. HTTPD::UserAdmin supports files used by the |
68dc0745 |
326 | `Basic' and `Digest' authentication schemes. Here's an example: |
327 | |
328 | use HTTPD::UserAdmin (); |
329 | HTTPD::UserAdmin |
330 | ->new(DB => "/foo/.htpasswd") |
331 | ->add($username => $password); |
332 | |
46fc3d4c |
333 | =head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things? |
334 | |
24f1ba9b |
335 | See the security references listed in the CGI Meta FAQ |
46fc3d4c |
336 | |
24f1ba9b |
337 | http://www.perl.org/CGI_MetaFAQ.html |
46fc3d4c |
338 | |
5a964f20 |
339 | =head2 How do I parse a mail header? |
68dc0745 |
340 | |
341 | For a quick-and-dirty solution, try this solution derived |
b73a15ae |
342 | from L<perlfunc/split>: |
68dc0745 |
343 | |
344 | $/ = ''; |
345 | $header = <MSG>; |
346 | $header =~ s/\n\s+/ /g; # merge continuation lines |
347 | %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header ); |
348 | |
349 | That solution doesn't do well if, for example, you're trying to |
350 | maintain all the Received lines. A more complete approach is to use |
351 | the Mail::Header module from CPAN (part of the MailTools package). |
352 | |
353 | =head2 How do I decode a CGI form? |
354 | |
7678cced |
355 | (contributed by brian d foy) |
356 | |
357 | Use the CGI.pm module that comes with Perl. It's quick, |
358 | it's easy, and it actually does quite a bit of work to |
359 | ensure things happen correctly. It handles GET, POST, and |
360 | HEAD requests, multipart forms, multivalued fields, query |
361 | string and message body combinations, and many other things |
362 | you probably don't want to think about. |
363 | |
364 | It doesn't get much easier: the CGI module automatically |
365 | parses the input and makes each value available through the |
366 | C<param()> function. |
367 | |
368 | use CGI qw(:standard); |
369 | |
370 | my $total = param( "price" ) + param( "shipping" ); |
371 | |
372 | my @items = param( "item ); # multiple values, same field name |
373 | |
374 | If you want an object-oriented approach, CGI.pm can do that too. |
375 | |
376 | use CGI; |
377 | |
378 | my $cgi = CGI->new(); |
379 | |
380 | my $total = $cgi->param( "price" ) + $cgi->param( "shipping" ); |
381 | |
382 | my @items = $cgi->param( "item" ); |
383 | |
384 | You might also try CGI::Minimal which is a lightweight version |
385 | of the same thing. Other CGI::* modules on CPAN might work better |
386 | for you, too. |
387 | |
388 | Many people try to write their own decoder (or copy one from |
389 | another program) and then run into one of the many "gotchas" |
390 | of the task. It's much easier and less hassle to use CGI.pm. |
68dc0745 |
391 | |
5a964f20 |
392 | =head2 How do I check a valid mail address? |
68dc0745 |
393 | |
c8db1d39 |
394 | You can't, at least, not in real time. Bummer, eh? |
68dc0745 |
395 | |
c8db1d39 |
396 | Without sending mail to the address and seeing whether there's a human |
c98c5709 |
397 | on the other end to answer you, you cannot determine whether a mail |
c8db1d39 |
398 | address is valid. Even if you apply the mail header standard, you |
399 | can have problems, because there are deliverable addresses that aren't |
400 | RFC-822 (the mail header standard) compliant, and addresses that aren't |
401 | deliverable which are compliant. |
68dc0745 |
402 | |
49d635f9 |
403 | You can use the Email::Valid or RFC::RFC822::Address which check |
404 | the format of the address, although they cannot actually tell you |
405 | if it is a deliverable address (i.e. that mail to the address |
406 | will not bounce). Modules like Mail::CheckUser and Mail::EXPN |
407 | try to interact with the domain name system or particular |
408 | mail servers to learn even more, but their methods do not |
409 | work everywhere---especially for security conscious administrators. |
410 | |
c8db1d39 |
411 | Many are tempted to try to eliminate many frequently-invalid |
d92eb7b0 |
412 | mail addresses with a simple regex, such as |
b8c8cfe2 |
413 | C</^[\w.-]+\@(?:[\w-]+\.)+\w+$/>. It's a very bad idea. However, |
c8db1d39 |
414 | this also throws out many valid ones, and says nothing about |
b8c8cfe2 |
415 | potential deliverability, so it is not suggested. Instead, see |
1577cd80 |
416 | http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz , |
68dc0745 |
417 | which actually checks against the full RFC spec (except for nested |
5a964f20 |
418 | comments), looks for addresses you may not wish to accept mail to |
68dc0745 |
419 | (say, Bill Clinton or your postmaster), and then makes sure that the |
c8db1d39 |
420 | hostname given can be looked up in the DNS MX records. It's not fast, |
421 | but it works for what it tries to do. |
422 | |
423 | Our best advice for verifying a person's mail address is to have them |
424 | enter their address twice, just as you normally do to change a password. |
425 | This usually weeds out typos. If both versions match, send |
426 | mail to that address with a personal message that looks somewhat like: |
427 | |
428 | Dear someuser@host.com, |
429 | |
430 | Please confirm the mail address you gave us Wed May 6 09:38:41 |
431 | MDT 1998 by replying to this message. Include the string |
432 | "Rumpelstiltskin" in that reply, but spelled in reverse; that is, |
433 | start with "Nik...". Once this is done, your confirmed address will |
434 | be entered into our records. |
435 | |
436 | If you get the message back and they've followed your directions, |
437 | you can be reasonably assured that it's real. |
68dc0745 |
438 | |
c8db1d39 |
439 | A related strategy that's less open to forgery is to give them a PIN |
440 | (personal ID number). Record the address and PIN (best that it be a |
441 | random one) for later processing. In the mail you send, ask them to |
442 | include the PIN in their reply. But if it bounces, or the message is |
443 | included via a ``vacation'' script, it'll be there anyway. So it's |
444 | best to ask them to mail back a slight alteration of the PIN, such as |
445 | with the characters reversed, one added or subtracted to each digit, etc. |
46fc3d4c |
446 | |
68dc0745 |
447 | =head2 How do I decode a MIME/BASE64 string? |
448 | |
6a0af2f1 |
449 | The MIME-Base64 package (available from CPAN) handles this as well as |
450 | the MIME/QP encoding. Decoding BASE64 becomes as simple as: |
68dc0745 |
451 | |
6a0af2f1 |
452 | use MIME::Base64; |
68dc0745 |
453 | $decoded = decode_base64($encoded); |
454 | |
26d9b02f |
455 | The MIME-Tools package (available from CPAN) supports extraction with |
6a0af2f1 |
456 | decoding of BASE64 encoded attachments and content directly from email |
457 | messages. |
458 | |
459 | If the string to decode is short (less than 84 bytes long) |
460 | a more direct approach is to use the unpack() function's "u" |
68dc0745 |
461 | format after minor transliterations: |
462 | |
463 | tr#A-Za-z0-9+/##cd; # remove non-base64 chars |
464 | tr#A-Za-z0-9+/# -_#; # convert to uuencoded format |
465 | $len = pack("c", 32 + 0.75*length); # compute length byte |
466 | print unpack("u", $len . $_); # uudecode and print |
467 | |
5a964f20 |
468 | =head2 How do I return the user's mail address? |
68dc0745 |
469 | |
a6dd486b |
470 | On systems that support getpwuid, the $< variable, and the |
68dc0745 |
471 | Sys::Hostname module (which is part of the standard perl distribution), |
472 | you can probably try using something like this: |
473 | |
474 | use Sys::Hostname; |
231ab6d1 |
475 | $address = sprintf('%s@%s', scalar getpwuid($<), hostname); |
68dc0745 |
476 | |
5a964f20 |
477 | Company policies on mail address can mean that this generates addresses |
478 | that the company's mail system will not accept, so you should ask for |
479 | users' mail addresses when this matters. Furthermore, not all systems |
68dc0745 |
480 | on which Perl runs are so forthcoming with this information as is Unix. |
481 | |
482 | The Mail::Util module from CPAN (part of the MailTools package) provides a |
483 | mailaddress() function that tries to guess the mail address of the user. |
484 | It makes a more intelligent guess than the code above, using information |
485 | given when the module was installed, but it could still be incorrect. |
486 | Again, the best way is often just to ask the user. |
487 | |
c8db1d39 |
488 | =head2 How do I send mail? |
68dc0745 |
489 | |
c8db1d39 |
490 | Use the C<sendmail> program directly: |
491 | |
492 | open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq") |
493 | or die "Can't fork for sendmail: $!\n"; |
494 | print SENDMAIL <<"EOF"; |
495 | From: User Originating Mail <me\@host> |
496 | To: Final Destination <you\@otherhost> |
497 | Subject: A relevant subject line |
498 | |
65acb1b1 |
499 | Body of the message goes here after the blank line |
500 | in as many lines as you like. |
c8db1d39 |
501 | EOF |
502 | close(SENDMAIL) or warn "sendmail didn't close nicely"; |
503 | |
504 | The B<-oi> option prevents sendmail from interpreting a line consisting |
505 | of a single dot as "end of message". The B<-t> option says to use the |
506 | headers to decide who to send the message to, and B<-odq> says to put |
507 | the message into the queue. This last option means your message won't |
508 | be immediately delivered, so leave it out if you want immediate |
509 | delivery. |
510 | |
d92eb7b0 |
511 | Alternate, less convenient approaches include calling mail (sometimes |
512 | called mailx) directly or simply opening up port 25 have having an |
513 | intimate conversation between just you and the remote SMTP daemon, |
514 | probably sendmail. |
515 | |
516 | Or you might be able use the CPAN module Mail::Mailer: |
c8db1d39 |
517 | |
518 | use Mail::Mailer; |
519 | |
520 | $mailer = Mail::Mailer->new(); |
521 | $mailer->open({ From => $from_address, |
522 | To => $to_address, |
523 | Subject => $subject, |
524 | }) |
525 | or die "Can't open: $!\n"; |
526 | print $mailer $body; |
527 | $mailer->close(); |
528 | |
529 | The Mail::Internet module uses Net::SMTP which is less Unix-centric than |
530 | Mail::Mailer, but less reliable. Avoid raw SMTP commands. There |
d92eb7b0 |
531 | are many reasons to use a mail transport agent like sendmail. These |
8305e449 |
532 | include queuing, MX records, and security. |
c8db1d39 |
533 | |
575cc754 |
534 | =head2 How do I use MIME to make an attachment to a mail message? |
535 | |
536 | This answer is extracted directly from the MIME::Lite documentation. |
537 | Create a multipart message (i.e., one with attachments). |
538 | |
539 | use MIME::Lite; |
540 | |
541 | ### Create a new multipart message: |
542 | $msg = MIME::Lite->new( |
543 | From =>'me@myhost.com', |
544 | To =>'you@yourhost.com', |
545 | Cc =>'some@other.com, some@more.com', |
546 | Subject =>'A message with 2 parts...', |
547 | Type =>'multipart/mixed' |
548 | ); |
549 | |
550 | ### Add parts (each "attach" has same arguments as "new"): |
551 | $msg->attach(Type =>'TEXT', |
552 | Data =>"Here's the GIF file you wanted" |
553 | ); |
554 | $msg->attach(Type =>'image/gif', |
555 | Path =>'aaa000123.gif', |
556 | Filename =>'logo.gif' |
557 | ); |
558 | |
559 | $text = $msg->as_string; |
560 | |
561 | MIME::Lite also includes a method for sending these things. |
562 | |
563 | $msg->send; |
564 | |
197aec24 |
565 | This defaults to using L<sendmail> but can be customized to use |
575cc754 |
566 | SMTP via L<Net::SMTP>. |
567 | |
c8db1d39 |
568 | =head2 How do I read mail? |
569 | |
d92eb7b0 |
570 | While you could use the Mail::Folder module from CPAN (part of the |
5cd0b561 |
571 | MailFolder package) or the Mail::Internet module from CPAN (part |
a6dd486b |
572 | of the MailTools package), often a module is overkill. Here's a |
d92eb7b0 |
573 | mail sorter. |
574 | |
575 | #!/usr/bin/perl |
5cd0b561 |
576 | |
c8db1d39 |
577 | my(@msgs, @sub); |
578 | my $msgno = -1; |
579 | $/ = ''; # paragraph reads |
580 | while (<>) { |
5cd0b561 |
581 | if (/^From /m) { |
c8db1d39 |
582 | /^Subject:\s*(?:Re:\s*)*(.*)/mi; |
583 | $sub[++$msgno] = lc($1) || ''; |
584 | } |
585 | $msgs[$msgno] .= $_; |
d92eb7b0 |
586 | } |
c8db1d39 |
587 | for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) { |
588 | print $msgs[$i]; |
589 | } |
590 | |
d92eb7b0 |
591 | Or more succinctly, |
c8db1d39 |
592 | |
593 | #!/usr/bin/perl -n00 |
594 | # bysub2 - awkish sort-by-subject |
595 | BEGIN { $msgno = -1 } |
596 | $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m; |
597 | $msg[$msgno] .= $_; |
598 | END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] } |
599 | |
68dc0745 |
600 | =head2 How do I find out my hostname/domainname/IP address? |
601 | |
c8db1d39 |
602 | The normal way to find your own hostname is to call the C<`hostname`> |
603 | program. While sometimes expedient, this has some problems, such as |
604 | not knowing whether you've got the canonical name or not. It's one of |
605 | those tradeoffs of convenience versus portability. |
68dc0745 |
606 | |
607 | The Sys::Hostname module (part of the standard perl distribution) will |
608 | give you the hostname after which you can find out the IP address |
609 | (assuming you have working DNS) with a gethostbyname() call. |
610 | |
611 | use Socket; |
612 | use Sys::Hostname; |
613 | my $host = hostname(); |
65acb1b1 |
614 | my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost')); |
68dc0745 |
615 | |
616 | Probably the simplest way to learn your DNS domain name is to grok |
617 | it out of /etc/resolv.conf, at least under Unix. Of course, this |
618 | assumes several things about your resolv.conf configuration, including |
619 | that it exists. |
620 | |
621 | (We still need a good DNS domain name-learning method for non-Unix |
622 | systems.) |
623 | |
624 | =head2 How do I fetch a news article or the active newsgroups? |
625 | |
626 | Use the Net::NNTP or News::NNTPClient modules, both available from CPAN. |
a6dd486b |
627 | This can make tasks like fetching the newsgroup list as simple as |
68dc0745 |
628 | |
629 | perl -MNews::NNTPClient |
630 | -e 'print News::NNTPClient->new->list("newsgroups")' |
631 | |
632 | =head2 How do I fetch/put an FTP file? |
633 | |
634 | LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also |
635 | available from CPAN) is more complex but can put as well as fetch. |
636 | |
637 | =head2 How can I do RPC in Perl? |
638 | |
a6dd486b |
639 | A DCE::RPC module is being developed (but is not yet available) and |
68dc0745 |
640 | will be released as part of the DCE-Perl package (available from |
65acb1b1 |
641 | CPAN). The rpcgen suite, available from CPAN/authors/id/JAKE/, is |
642 | an RPC stub generator and includes an RPC::ONC module. |
68dc0745 |
643 | |
644 | =head1 AUTHOR AND COPYRIGHT |
645 | |
7678cced |
646 | Copyright (c) 1997-2005 Tom Christiansen, Nathan Torkington, and |
647 | other authors as noted. All rights reserved. |
5a964f20 |
648 | |
5a7beb56 |
649 | This documentation is free; you can redistribute it and/or modify it |
650 | under the same terms as Perl itself. |
5a964f20 |
651 | |
652 | Irrespective of its distribution, all code examples in this file |
653 | are hereby placed into the public domain. You are permitted and |
654 | encouraged to use this code in your own programs for fun |
655 | or for profit as you see fit. A simple comment in the code giving |
656 | credit would be courteous but is not required. |