Java Requires Chilkat v11.0.0+
Chilkat2 Java
Forward by Attaching the Existing Email to a New Email
See more Email Object Examples
Demonstrates how to forward an email by attaching the email to a new email.This example reads an email from an IMAP server, attaches the email to a new email, and sends the new email.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.Imap;
import com.chilkatsoft.chilkat2.MailMan;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Read the 1st (most recent) email in an Inbox.
Imap imap = new Imap();
// Connect to an IMAP server.
imap.setSsl(true);
imap.setPort(993);
try {
imap.connect("imap.example.com");
// Login
imap.login("myLogin", "myPassword");
// Select an IMAP mailbox
imap.selectMailbox("Inbox");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
int numEmails = imap.getNumMessages();
// Fetch the email at the last sequence number.
// (We are assuming the Inbox has at least 1 email)
Email email = new Email();
try {
imap.fetchEmail(false, numEmails, false, email);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Disconnect from the IMAP server.
imap.disconnect();
System.out.println(email.getSubject());
// Create a new email. The email we just read will be attached to this email.
Email eForward = new Email();
eForward.addTo("Joe", "joe@example.com");
eForward.setFromAddress("matt@somewhere.com");
eForward.setFromName("Matt");
eForward.setSubject("This is an email with another email attached.");
eForward.setHtmlBody("<p>Hello, this is an email I'm forwarding to you. See the attached email.</p>");
// Attach the email.
eForward.attachEmail(email);
// We could save the .eml, then double-click on it to view in our mail program, such as Outlook or Thunderbird..
eForward.saveEml("qa_output/forward.eml");
// We could send (forward) the email..
MailMan mailman = new MailMan();
mailman.setSmtpHost("smtp.example.com");
mailman.setSmtpUsername("myLogin");
mailman.setSmtpPassword("myPassword");
mailman.setSmtpPort(587);
mailman.setStartTLS(true);
try {
mailman.sendEmail(eForward);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
try {
mailman.closeSmtpConnection();
} catch (ChilkatException e) {
System.out.println("Connection to SMTP server not closed cleanly.");
}
System.out.println("Mail Sent!");
}
}