001/**************************************************************** 002 * Licensed to the Apache Software Foundation (ASF) under one * 003 * or more contributor license agreements. See the NOTICE file * 004 * distributed with this work for additional information * 005 * regarding copyright ownership. The ASF licenses this file * 006 * to you under the Apache License, Version 2.0 (the * 007 * "License"); you may not use this file except in compliance * 008 * with the License. You may obtain a copy of the License at * 009 * * 010 * http://www.apache.org/licenses/LICENSE-2.0 * 011 * * 012 * Unless required by applicable law or agreed to in writing, * 013 * software distributed under the License is distributed on an * 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * 015 * KIND, either express or implied. See the License for the * 016 * specific language governing permissions and limitations * 017 * under the License. * 018 ****************************************************************/ 019 020package org.apache.james.mime4j.samples.dom; 021 022import java.io.IOException; 023import java.util.Date; 024 025import org.apache.james.mime4j.dom.MessageWriter; 026import org.apache.james.mime4j.dom.TextBody; 027import org.apache.james.mime4j.field.address.AddressBuilder; 028import org.apache.james.mime4j.field.address.ParseException; 029import org.apache.james.mime4j.message.MessageImpl; 030import org.apache.james.mime4j.message.DefaultMessageWriter; 031import org.apache.james.mime4j.storage.StorageBodyFactory; 032 033/** 034 * This example generates a message very similar to the one from RFC 5322 035 * Appendix A.1.1. 036 */ 037public class TextPlainMessage { 038 public static void main(String[] args) throws IOException, ParseException { 039 // 1) start with an empty message 040 041 MessageImpl message = new MessageImpl(); 042 043 // 2) set header fields 044 045 // Date and From are required fields 046 message.setDate(new Date()); 047 message.setFrom(AddressBuilder.DEFAULT.parseMailbox("John Doe <jdoe@machine.example>")); 048 049 // Message-ID should be present 050 message.createMessageId("machine.example"); 051 052 // set some optional fields 053 message.setTo(AddressBuilder.DEFAULT.parseMailbox("Mary Smith <mary@example.net>")); 054 message.setSubject("Saying Hello"); 055 056 // 3) set a text body 057 058 StorageBodyFactory bodyFactory = new StorageBodyFactory(); 059 TextBody body = bodyFactory.textBody("This is a message just to " 060 + "say hello.\r\nSo, \"Hello\"."); 061 062 // note that setText also sets the Content-Type header field 063 message.setText(body); 064 065 // 4) print message to standard output 066 067 MessageWriter writer = new DefaultMessageWriter(); 068 writer.writeMessage(message, System.out); 069 070 // 5) message is no longer needed and should be disposed of 071 072 message.dispose(); 073 } 074}