Asked  7 Months ago    Answers:  5   Viewed   36 times

Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.

 Answers

94

First download the JavaMail API and make sure the relevant jar files are in your classpath.

Here's a full working example using GMail.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Main {

    private static String USER_NAME = "*****";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "********"; // GMail password
    private static String RECIPIENT = "lizard.bill@myschool.edu";

    public static void main(String[] args) {
        String from = USER_NAME;
        String pass = PASSWORD;
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Java send mail example";
        String body = "Welcome to JavaMail!";

        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }
}

Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)


Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.

Tuesday, June 1, 2021
 
HexaGridBrain
answered 7 Months ago
90

For sending out the actual e-mail I would recommend using the PHPMailer library, it makes everything much easier.

Thursday, July 29, 2021
 
Isky
answered 5 Months ago
24

According to JM developer Bill Shannon, this is a limitation of the IMAP protocol:

from    Bill Shannon 
to  Jonathan Hanson 
cc  javamail_ww@oracle.com
date    Wed, Aug 10, 2011 at 11:55 AM
subject Re: Bug with searching by ReceivedDateTerms
mailed-by   oracle.com
    Important mainly because of your interaction with messages in the conversation.

hide details 11:55 AM (16 minutes ago)

The searching is being done by the IMAP server, and you're running into a limitation of the IMAP protocol.
Wednesday, August 11, 2021
 
Mountains
answered 4 Months ago
78
Flags processedFlag = new Flags("processed");
folder.setFlags(msgs, processedFlag, true);
// or
msg.setFlags(processedFlag, true);

Not all IMAP servers will support these "user flags", but most will. To find messages without this flag:

Message[] msgs = folder.search(new FlagTerm(processedFlag, false));
Thursday, August 12, 2021
 
Yrtymd
answered 4 Months ago
88

Here is the code:

- (void) sendToMail:(NSString *)mailingList

{

    NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:STATS_FILE];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    mailingList = MAILING_LIST;



    if ([fileManager fileExistsAtPath:filePath])

    {

        // Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.

        NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];

        [_params setObject:@"xxxx@xxxx.xxx" forKey:@"FromEmail"];

        [_params setObject:@"xxx xxx xxxx" forKey:@"FromName"];

        [_params setObject:@"xxx xxx xxx" forKey:@"Subject"];

        [_params setObject:@"xxx xxxx xxxx" forKey:@"Html-part"];

        //mail(s) treatment

        NSUInteger numberOfOccurrences = [[mailingList componentsSeparatedByString:@";"] count] - 1;

        NSArray *subStrings = [mailingList componentsSeparatedByString:@";"];

        NSMutableArray *mailsArr = [NSMutableArray new];



        for (int i=0; i<=numberOfOccurrences; i++)

        {

            NSString *mail = [subStrings objectAtIndex:i];

            if ([self validEmail:mail])

               [mailsArr addObject:@{@"Email":mail}];

        }



        if ([mailsArr count] > 0)

           [_params setObject:mailsArr forKey:@"Recipients"];



        //add any attachment file to JSON

        NSData* data = [NSData dataWithContentsOfFile:filePath];

        if (data)

        {

            NSString *encodedString = [data base64EncodedStringWithOptions:0];

            NSArray *attachmentsArr = @[@{@"Content-type":@"text/plain", @"Filename":[NSString stringWithFormat:@"%@.db", [[[UIDevice currentDevice] identifierForVendor] UUIDString]], @"content":encodedString}];

            [_params setObject:attachmentsArr forKey:@"Attachments"];

        }



        // the server url to which the image (or the media) is uploaded. Use your server url here

        NSURL* requestURL = [NSURL URLWithString:@"https://api.mailjet.com/v3/send/"];



        // create request

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

        [request setHTTPShouldHandleCookies:NO];

        [request setTimeoutInterval:30];

        [request setHTTPMethod:@"POST"];



        //HTTP Basic Authentication

        NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", API_KEY, SECRET_KEY];

        NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];

        NSString *authenticationValue = [authenticationData base64EncodedStringWithOptions:0];

        [request setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"];



        NSString *jsonRequest = [_params JSONRepresentation];

        NSLog(@"jsonRequest is %@", jsonRequest);



        NSMutableData *requestData = [[jsonRequest dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];

        [request setHTTPMethod:@"POST"];

        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];



        // setting the body of the post to the request

        [request setHTTPBody:requestData];



        // set the content-length

        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]];

        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

        [request setURL:requestURL]; // set URL



        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

        [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

            NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

#if DEBUG

            NSLog(@"requestReply: %@, error: %@", requestReply, error);

#endif

            if (error == nil)

            {

                [self showAlertWithMessage:@"File sent!" withButton:@"Ok!"];

            }

            else

            {

                [self showAlertWithMessage:@"Could not send file!" withButton:@"Ok!"];

            }

        }] resume];

    }
Wednesday, December 1, 2021
 
nbulba
answered 3 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share