working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,794 snippets matching: gmail

    public by cghersi  5835  1  8  3

    How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

    This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form. The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified in the static constant "s_
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Google.Contacts;
    using Google.GData.Contacts;
    using Google.GData.Client;
    using Google.GData.Extensions;
    
    namespace Contact.Utils
    {
      /// <summary>
      /// Summary description for GmailHelper
      /// </summary>
      public class GmailHelper
      {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils();
    
        private static readonly string APP_NAME = "my app name";
        private static readonly string s_ClientId = "client id given by Google";
        private static readonly string s_ClientSecret = "secret given by Google;
        private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
        private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback";
    
        #region PUBLIC API
        //////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public static string GetRedirUriForContacts()
        {
          return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}",
            s_redirUri, s_ClientId);
        }
    
        public static List<SimpleContact> GetContacts(string token)
        {
          List<SimpleContact> results = new List<SimpleContact>();
    
          //exchange the code for a token:
          string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
            token, s_ClientId, s_ClientSecret, s_redirUri);
          string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true);
          if (string.IsNullOrEmpty(accessTokenResp))
            return results;
    
          AccessTokenStruct parsedJson = null;
          try
          {
            parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); 
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message);
            return results;
          }
          if (parsedJson == null)
            return results;
    
          //ask for contacts:
          RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); 
          settings.AutoPaging = true;
          ContactsRequest cr = new ContactsRequest(settings);
          Feed<Contact> contactsFeed = cr.GetContacts();
          IEnumerable<Contact> contacts = null;
          if (contactsFeed != null)
            contacts = contactsFeed.Entries;
          if (contacts == null)
            return results;
    
          try
          {
            foreach (SimpleContact c in contacts)
            {
              if (c.PrimaryEmail == null)
                continue;
              string preferredEmail = c.PrimaryEmail.Address;
              if (string.IsNullOrEmpty(preferredEmail))
                continue;
              string[] otherEmails = null;
              if (c.Emails != null)
                otherEmails = c.Emails.Select(e => e.Address).ToArray();
              S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), 
                                                  preferredEmail, otherEmails);
              results.Add(contact);
            }
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message);
            return results;
          }
    
          return results;
        }
    
        #endregion
        //////////////////////////////////////////////////////////////////////////////////////////////////////
      }
    
      public class AccessTokenStruct
      {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
    
        public AccessTokenStruct() { }
      }
    
      public class SimpleContact
      {
        public string PreferredEmail { get; set; }
        public string Name { get; set; }
        public string[] Emails { get; set; }
    
        public SimpleContact(string name, string preferredEmail, string[] emails = null)
        {
          Name = name;
          PreferredEmail = preferredEmail;
          if (emails == null)
            Emails = new string[] { preferredEmail };
          else
          {
            List<string> allEmails = new List<string>(emails);
            allEmails.Add(preferredEmail);
            Emails = allEmails.Distinct().ToArray();
          }
        }
    
        public override string ToString()
        {
          if (string.IsNullOrEmpty(Name))
            return PreferredEmail;
          else
            return string.Format("{0} [{1}]", Name, PreferredEmail);
        }
      }
    
    }            

    public by Mk47  2742  3  5  2

    Sending multiple email using Java ( Using Gmail SMTP )

    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class JavaEmail
    {
        Session mailSession;
    
        public static void main(String args[]) throws AddressException,    MessagingException
        {
            JavaEmail javaEmail = new JavaEmail();
            javaEmail.setMailServerProperties();
            javaEmail.draftEmailMessage();
            javaEmail.sendEmail();
        }
    
        private void setMailServerProperties()
        {
            Properties emailProperties = System.getProperties();
            emailProperties.put("mail.smtp.port", "587");
            emailProperties.put("mail.smtp.auth", "true");
            emailProperties.put("mail.smtp.starttls.enable", "true");
            mailSession = Session.getDefaultInstance(emailProperties, null);
        }
    
        private MimeMessage draftEmailMessage() throws AddressException, MessagingException
        {
            String[] toEmails = { "Google@gmail.com" };
            String emailSubject = "Test email subject";
            String emailBody = "This is a test message";
            MimeMessage emailMessage = new MimeMessage(mailSession);
            /**
             * Set the mail recipients
             * */
            for (int i = 0; i < toEmails.length; i++)
            {
                emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
            }
            emailMessage.setSubject(emailSubject);
            /**
             * If sending HTML mail
             * */
            emailMessage.setContent(emailBody, "text/html");
            /**
             * If sending only text mail
             * */
            //emailMessage.setText(emailBody);// for a text email
            return emailMessage;
        }
    
        private void sendEmail() throws AddressException, MessagingException
        {
            /**
             * Sender's credentials
             * */
            String fromUser = "user-email@gmail.com";
            String fromUserEmailPassword = "*******";
    
            String emailHost = "smtp.gmail.com";
            Transport transport = mailSession.getTransport("smtp");
            transport.connect(emailHost, fromUser, fromUserEmailPassword);
            /**
             * Draft the message
             * */
            MimeMessage emailMessage = draftEmailMessage();
            /**
             * Send the mail
             * */
            transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
            transport.close();
            System.out.println("Email sent successfully.");
        }
    }  

    public by robertthomasmaster  2745  0  6  0

    Gmail helpline number Gmail helpdesk

    Gmail helpdesk Check Out :- http://www.gmail-support-number.com/
    Gmail helpline number  Check Out :- http://www.gmail-support-number.com/gmail-customer-service.html
             

    public by alinros  1787  0  5  1

    Problem and errors with Gmail! Go using any mobile

    Various Gmail problems are known to every account user now. There are a large Gmail Phone Number of individuals who are used to have problems in their account while operating their Gmail accounts via their desktop or mobile.
    For More Information: http://gmail-phone-number.com/

    public by alinros  1861  0  5  0

    Anyone else having import issues from Gmail?

    Sometimes importing mails from Gmail can be a problem and you can resolve the issue by calling the Gmail technical members. They have the best solutions available with them which can be resolved by calling the Gmail Technical Support team. The technical associates of Gmail are highly professional and they
    For More Information: http://www.gmail-phone-number.com/Gmail-Technical-Support.html

    public by fukusuke1026  951  0  3  0

    とどシステム用 ・CSVデータの置換 ・Gmailから添付してメール送信

    とどシステム用 ・CSVデータの置換 ・Gmailから添付してメール送信: gistfile1.pl
    use strict;
    use warnings;
    use utf8;
    use open ":encoding(cp932)";
    use open ":std";
    use Try::Tiny;
    use IO::All;
    use Email::MIME;
    use Email::Sender::Simple qw(sendmail);
    use Email::Sender::Transport::SMTP::TLS;
    use Getopt::Std;
    use vars qw(
                $opt_t 
                $opt_f 
                $opt_p 
                $opt_d 
                );
    
    use Encode;
    ### オプション設定
    if(!getopts("t:f:p:d:")) {
       print "パラメータが設定されていません。\n";
       exit (1);
    }
    
    
    ###CSVデータ置換処理
    chdir($opt_d);
    my @csv = glob '*.csv';
    my $mail_sub;
    foreach my $csv (@csv){
    	open CSV,"$csv";
    	
    	$csv=~ s/\.csv//g;
    	$mail_sub = $csv;
    	
    	my($mday,$mon,$year) = (localtime(time))[3..5];
    	$year += 1900;
    	$mon += 1;
    	my $date = sprintf("-%02d-%02d-%02d", $year, $mon, $mday);
    	$csv = $csv.$date;
    	
    	my $excludecsv = $csv."EXCLUDE.csv";
    	my $tellcsv = $csv."TELL.csv";
    	open EXLIST  , "> $excludecsv";
    	open OUT , "> $tellcsv";
    
    	#######################################
    	#データの文字列の判定処理
    	#######################################
    	
    	while ( my $line = <CSV> )
    	{
    	  	my @cols = split(/,/, $line);
    		my $address = $cols[3];
    		
    		if($address =~ /^.*[A-Z].*/){
    			#全角アルファベット
    			print EXLIST $line;
    		}elsif($address =~ /^.*[A-z].*/){
    			#半角アルファベット
    			print EXLIST $line;
    		}elsif($address =~ /^.*[ァ-ヶ].*/){
    			#全角カタカタ
    			print EXLIST $line;
    		}elsif($address =~ /^.*[ア-ン].*/){
    			#半角カタカタ
    			print EXLIST $line;
    		}elsif($address =~ /^.*(団地|住宅).*/){
    			#団地/住宅
    			print EXLIST $line;
    		}elsif($address =~ /^.*[市公都県民]営.*/){
    			#市・県・都・公 営
    			print EXLIST $line;
    		}elsif($address =~ /^[^-]+-([0-9]+-)*?[A-Z]?[1-9]0[1-9]/){
    			#全角:末尾が103のような形式
    			print EXLIST $line;
    		}elsif($address =~ /^[^-]+-([0-9]+-)*?[A-z]?[1-9]0[1-9]/){
    			#半角:末尾が103のような形式
    			print EXLIST $line;
    		}else{
    			print OUT $line;
    		}
    	}
    	 
    	close EXLIST;
    	close OUT;
    	close CSV;
    	
    	print "CSVデータのデータ変換が完了しました。\n";
    	
    	#######################################
    	#Gmail送信処理
    	#######################################
    
    	# Create and array of email parts. 
    	# Here i have 2 attachments ( an image and a pdf file) and a text message.
    		my @parts = (
    		Email::MIME->create(
    		    attributes => {
    		        filename      => "$excludecsv",
    		        content_type  => "text/csv",
    		        encoding      => "base64",
    		        disposition   => "attachment",
    		        charset       => "ISO-2022-JP",
    		        Name          => "aaa.csv"
    		    },
    		    body => io( "$excludecsv" )->all,
    		),
    		Email::MIME->create(
    		    attributes => {
    		        filename     => "$tellcsv",
    		        content_type => "text/csv",
    		        encoding     => "base64",
    		        disposition  => "attachment",
    		        charset       => "ISO-2022-JP",
    		        name         => "bbb.csv",
    		    },
    		    body => io( "$tellcsv" )->all,
    		),
    		Email::MIME->create(
    		    attributes => {
    		    	charset       => "ISO-2022-JP",
    		        content_type  => "text/html",
    		    },
    		    body => "$mail_sub",
    		)
    		);
    
    	# Create the email message object.
    		my $email_object = Email::MIME->create(
    		header => [
    		    From           => "$opt_f",
    		    To             => "$opt_t",
    		    Subject => encode('MIME-Header-ISO_2022_JP' => '本日分の発信先リストのご案内'),
    		    content_type   =>'multipart/mixed',
    		    charset       => "ISO-2022-JP"
    		],
    		parts  => [ @parts ],
    		);
    
    	# Create the transport. Using gmail for this example
    		my $transport = Email::Sender::Transport::SMTP::TLS->new(
    		host     => 'smtp.gmail.com',
    		port     => 587,
    		username => "$opt_f",
    		password => "$opt_p"
    	);
    
    	# send the mail
    		try {
    		   sendmail( $email_object, {transport => $transport} );
    		} catch {
    		   warn "Email sending failed: $_";
    		};
    		
    		print "メール送信処理が完了しました。\n";
    }
    
    ##ファイル削除
    my @delcsv = glob '*.csv';
    foreach my $delcsv (@delcsv){
    	unlink $delcsv;
    }
    
    
    

    public by paulsimmons  661  2  4  0

    Magento Facebook Login Extension by FMEAddons

    Magento Facebook login extension by FMEAddons allows the customers to connect on your website by using their Facebook profile. This addon enables 4 social login buttons on registration page which are Facebook, Twitter, Yahoo, and Gmail. Customers can select any of these social accounts to get the login to your website. Customers can now place the o
    // Enter here the actual content of the snippet.            

    external by Davide  1006612  369  4  0

    React Big Calendar (https://github.com/jquense/react-big-calendar) is a fantastic outlook / gmail style calendar. Unfortunately hasn't a good documentation and example code. There is one inspired from Example folder :)

    React Big Calendar (https://github.com/jquense/react-big-calendar) is a fantastic outlook / gmail style calendar. Unfortunately hasn't a good documentation and example code. There is one inspired from Example folder :): Planner.jsx
    import React from 'react';
    import { Glyphicon, Col, Row } from 'react-bootstrap';
    import BigCalendarCSS from 'react-big-calendar/lib/css/react-big-calendar.css';
    import BigCalendar from 'react-big-calendar';
    import Moment from 'moment';
    import Events from 'Events.jsx'; // https://github.com/jquense/react-big-calendar/blob/master/examples/events.js 
    
    export default class Planner extends React.Component {
        constructor(props, context)
        {
            super(props, context);
            this.context = context;
            this.state = {events: Events};
            BigCalendar.setLocalizer(
                    BigCalendar.momentLocalizer(moment)
            );
        }
    
        handleSelectSlot({start, end})
        {
            //create an event with title "Test"
            console.log("handleSelectSlot: " + start + " - " + end);
            this.state.events.push({start: start, end: end, title: "Test"});
            this.setState({});
    
        }
    
        handleSelectEvent()
        {
            //just for example
            console.log("handleSelectEvent: " + JSON.stringify(arguments));
        }
    
        EventWeek(props)
        {
            return <strong>{props.event.title}</strong>
        }
    
        EventAgenda(props)
        {
            return <em>{props.event.title}</em>
        }
    
        render()
        {
            return (<div>
                    <BigCalendar
                            selectable
                            popup
                            events={this.state.events}
                            onSelectSlot={this.handleSelectSlot.bind(this)}
                            onSelectEvent={this.handleSelectEvent.bind(this)}
                            defaultDate={new Date(2015, 3, 1)}
                            eventPropGetter={e => ({ className: 'test-class'})} /* Here you can define a style for the element */
                            components={{
                  event: this.EventWeek,
                  agenda: {
                    event: this.EventAgenda
                  }
                }}
                            />
            </div>);
        }
    }
    
    
    

    external by YourWebDevGuy  489359  34  4  0

    Sort Gmail Inbox (Primary Tab)

    Sort Gmail Inbox (Primary Tab): sortGmail.js
    !function(){function e(e){var t,n,a,r,l=e.getElementsByTagName("td");for(a=0;a<l.length;a++){if("yX xY "==l[a].className)for(t=l[a].getElementsByTagName("div"),r=0;r<t.length;r++)if("yW"==t[r].className&&(n=t[r].getElementsByTagName("span"),n.length))return n[0].innerHTML;if(l[a].hasAttribute("role")&&"link"==l[a].getAttribute("role"))for(t=l[a].getElementsByTagName("div"),r=0;r<t.length;r++)if("y6"==t[r].className&&(n=t[r].getElementsByTagName("span"),n.length))return n[0].innerHTML}return""}function t(e,t){return e=e[0].toLowerCase(),t=t[0].toLowerCase(),t>e?-1:e>t?1:0}function n(n){var a=Array.prototype.slice.call(n.getElementsByTagName("tr"),0);if(a.length){for(var r=a[0].parentNode,l=[],g=0;g<a.length;g++)l[g]=[e(a[g]),a[g]];for(l=l.sort(t),g=0;g<l.length;g++)r.appendChild(l[g][1])}}for(var a=document.getElementsByTagName("table"),r=0;r<a.length;r++)if("F cf zt"==a[r].className){n(a[r]);break}}();
    
    

    external by derwiki  68  0  1  0

    Ruby script utilizing the ruby-gmail gem that allows for searching and downloading Gmail messages by label. This implementation is looking for invoice emails and parsing the amount of money that was transferred.

    Ruby script utilizing the ruby-gmail gem that allows for searching and downloading Gmail messages by label. This implementation is looking for invoice emails and parsing the amount of money that was transferred.: gmail-invoice-parse.rb
    require 'gmail'
    
    label = 'transactional/payment'
    Gmail.new(username, password) do |gmail|
      puts "Emails that match label '#{ label }'"
      lender_profit = 0
      gmail.mailbox(label).emails.each do |email|
        message = email.message
        next if message.subject =~ /^Re: /
        next if message.subject =~ /^Fwd: /
    
        timestamp = message.date.to_time.to_i
        recipient_email = if message.to.is_a?(Enumerable)
                            message.to.first
                          else
                            message.to
                          end
    
        match = message.body.to_s[/your profit:\n\-?\$([0-9\.]*)/] ||
                message.body.to_s[/for a total of\n\$([0-9\.]*)/]
    
        # before 2013-06-03, we didn't put the profit rate in emails
        next if match.nil?
    
        profit = match.split('$').last.to_f
        profit *= -1 if match.include?(?-)
    
        puts [ timestamp, recipient_email, profit ].join(',')
    
        lender_profit += profit
      end
      puts "Total lender profit: $#{ lender_profit.round(2) }"
    end
    
    
    • Public Snippets
    • Channels Snippets