Ejemplo n.º 1
0
/**
 * send email
 * @param {[type]} r     *http.Request     [description]
 * @param {[type]} model string            [description]
 * @param {[type]} data  map[string]string data to fo to template
 * @param {[type]} sub   string            subject
 * @param {[type]} to    string            receiver email
 * @param {[type]} from  string            sender email
 */
func SendEmail(r *http.Request, model string, data map[string]string, sub string, to string, from string) error {
	templateFile, err := ioutil.ReadFile("email_templates/" + model)
	if err != nil {
		return err
	}
	templateString := string(templateFile)
	tmpl, err := template.New("email").Parse(templateString)
	if err != nil {
		return err
	}
	var doc bytes.Buffer
	err = tmpl.Execute(&doc, data)
	if err != nil {
		return err
	}
	body := doc.String()
	c := appengine.NewContext(r)
	msg := &mail.Message{
		Sender:   "Call For Paper <" + from + ">",
		To:       []string{to},
		Subject:  sub,
		HTMLBody: body,
	}
	if err := mail.Send(c, msg); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 2
0
func SendMail(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	vars := mux.Vars(r)
	address := vars["email"]

	m := &mail.Message{
		Sender: "kyokomi-dev<*****@*****.**>",
		//		ReplyTo: "",
		To: []string{address},
		//		Cc: "",
		//		Bcc: []string{},
		Subject:  "Test Mail",
		Body:     "サンプルメールを送信。",
		HTMLBody: "",
		//		Attachments: []Attachment{},
		//		Headers: mail.Header{},
	}

	if err := mail.Send(c, m); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/", http.StatusFound)
}
Ejemplo n.º 3
0
func TriggerSubscriptionsIfNeeded(check alert.Check, subscriptions []Subscription, context appengine.Context) {
	for _, subscription := range subscriptions {

		if check.Changed && check.CurrentState > check.PreviousState {
			log.Infof(context, "Firing Subscrption %v", subscription)

			subject := fmt.Sprintf("Alert %s changed state from %s to %s", check.Alert,
				alert.GetStateString(check.PreviousState), alert.GetStateString(check.CurrentState))

			message := fmt.Sprintf("Alert %s changed state from %s to %s with value %f\n Value measured at %s.\n", check.Alert,
				alert.GetStateString(check.PreviousState), alert.GetStateString(check.CurrentState),
				check.Value, time.Now().UTC().String())

			msg := &mail.Message{
				Sender:  "Klaxon <*****@*****.**>",
				To:      []string{subscription.Target},
				Subject: subject,
				Body:    message,
			}
			if err := mail.Send(context, msg); err != nil {
				log.Errorf(context, "Couldn't send email: %v", err)
			}
		}

	}
}
Ejemplo n.º 4
0
func handleSendPage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	//addr := r.FormValue("email")
	//url := createConfirmationURL(r)
	params, err := parseTemplateParams()
	if err != nil {
		c.Errorf("template execution: %s", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	c.Infof("Sender:", fmt.Sprintf(templateMailFrom, params.MailSenderName, params.MailSenderEmail))

	addrs := []string{"*****@*****.**"}

	msg := &mail.Message{
		Sender:  fmt.Sprintf(templateMailFrom, params.MailSenderName, params.MailSenderEmail),
		To:      addrs,
		Subject: "Confirm your registration",
		Body:    fmt.Sprintf(confirmMessage, "Test text"),
	}

	if err := mail.Send(c, msg); err != nil {
		c.Errorf("template execution: %s", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Ejemplo n.º 5
0
func sendReminder(c appengine.Context, date time.Time) {
	addr := "*****@*****.**"

	tag := fmt.Sprintf("diaryentry%dtag", rand.Int63())

	item := &memcache.Item{
		Key:   tag,
		Value: []byte(date.Format(time.RFC850)),
	}

	// Add the item to the memcache, if the key does not already exist
	if err := memcache.Add(c, item); err == memcache.ErrNotStored {
		c.Infof("item with key %q already exists", item.Key)
	} else if err != nil {
		c.Errorf("error adding item: %v", err)
	}

	msg := &mail.Message{
		Sender:  "Automatic Diary <*****@*****.**>",
		To:      []string{addr},
		Subject: "Entry reminder",
		Body:    fmt.Sprintf(reminderMessage, tag),
	}
	if err := mail.Send(c, msg); err != nil {
		c.Errorf("Couldn't send email: %v", err)
		return
	}
	c.Infof("Reminder mail sent for %v", date)
	c.Infof("body: %v", msg.Body)
}
Ejemplo n.º 6
0
func doInitiateResetPassword(email string, c *Context) error {
	// Check that it's a known user email.
	userId, user := GetUserFromEmailOrDie(email, c)

	// Create the ResetPassword record.
	v := &ResetPassword{
		UserId:    userId,
		Timestamp: time.Now(),
	}
	key := NewEphemeralKey(c.Aec(), "ResetPassword")
	key, err := datastore.Put(c.Aec(), key, v)
	if err != nil {
		return err
	}

	// Send the email.
	resetUrl := prependHost(fmt.Sprintf("/account/change-password?key=%s", key.Encode()), c)
	data := map[string]interface{}{
		"fullName": user.FullName,
		"email":    user.Email,
		"resetUrl": resetUrl,
	}
	body, err := ExecuteTextTemplate("email-reset-password.txt", data)
	if err != nil {
		return err
	}

	msg := &mail.Message{
		Sender:  "Tadue <*****@*****.**>",
		To:      []string{user.Email},
		Subject: "Reset your Tadue password",
		Body:    body,
	}
	return mail.Send(c.Aec(), msg)
}
Ejemplo n.º 7
0
// sendAlert sends an alert email about the potential car hijacking.
func sendAlert(c appengine.Context, accKeyID int64, alertMsg, bodyTempl string) {
	// load account
	acc := new(ds.Account)
	key := datastore.NewKey(c, ds.ENameAccount, "", accKeyID, nil)
	if err := datastore.Get(c, key, acc); err != nil {
		c.Errorf("Failed to load account: %v", err)
		return
	}

	const adminEmail = "Andras Belicza <*****@*****.**>"
	msg := &mail.Message{
		Sender:  adminEmail,
		To:      []string{acc.Email},
		ReplyTo: adminEmail,
		Subject: "[IczaGPS] ALERT: " + alertMsg,
		Body:    fmt.Sprintf(bodyTempl, acc.Email),
	}
	if len(acc.ContactEmail) > 0 {
		msg.Cc = []string{acc.ContactEmail}
	}
	if err := mail.Send(c, msg); err == nil {
		c.Infof("Sent successful alert email: %s", alertMsg)
	} else {
		c.Errorf("Couldn't send alert email: %s, %v", alertMsg, err)
	}
}
Ejemplo n.º 8
0
// Sends an email to the author of part with a link to continue.
func sendMail(c appengine.Context, story Story) {
	if story.Complete {
		return
	}
	var subject, text string
	part := story.LastPart()
	url := fmt.Sprintf(serverUrl, story.Id, story.NextId)
	if part != nil {
		subject = "Please write the next part of this story."
		text = fmt.Sprintf("%s, %s wrote:\n> %s\n\nPlease visit %s to write the next part.",
			capital(fuzzyTime(part.Written)), getFullEmail(c, part.Author), part.Visible, url)
	} else {
		subject = "Please write the first part of this story."
		text = fmt.Sprintf("%s, %s initiated a new story.\n\nPlease visit %s to write the beginning.",
			capital(fuzzyTime(story.Created)), getFullEmail(c, story.Creator), url)
	}

	msg := &mail.Message{
		Sender:  sender,
		To:      []string{story.NextAuthor},
		Subject: subject,
		Body:    text,
	}
	if err := mail.Send(c, msg); err != nil {
		c.Errorf("Couldn't send email: %v", err)
		panic(err)
	}
}
Ejemplo n.º 9
0
func unregisterUser(addr string, c appengine.Context) {
	q := datastore.NewQuery(USER_MODEL).
		Filter("Email =", addr).
		KeysOnly()
	keys, err := q.GetAll(c, nil)
	if err != nil {
		c.Errorf("Cound not query the model for %s: %v", addr, err)
		return
	}
	if len(keys) == 0 {
		c.Infof("No such user to unregister: %s", addr)
		return
	}
	for i := range keys {
		datastore.Delete(c, keys[i])
	}
	c.Infof("Removed user %s", addr)

	msg := &gaeMail.Message{
		Sender:  "*****@*****.**",
		To:      []string{addr},
		Subject: "Email unregistered",
		Body:    "user " + addr + " has been unregistered",
	}
	gaeMail.Send(c, msg)
}
Ejemplo n.º 10
0
func submit(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	name := r.FormValue("name")
	email := r.FormValue("email")
	message := "<html><body><h3>Contact:</h3><p>Phone: " + r.FormValue("phone") + "<br/>Message: " + r.FormValue("message") + "</p><h3>Order:</h3><p>" + r.FormValue("order") + "</p></body></html>"
	msg := &mail.Message{
		Sender:  name + " <*****@*****.**>",
		To:      []string{"*****@*****.**"},
		ReplyTo: email,
		Subject: "DCHCM Received New Order",
		//Body:    message,
		HTMLBody: message,
		Headers: netMail.Header{
			//"Content-Type": []string{"text/html; charset=UTF-8"},
			"On-Behalf-Of": []string{email},
		},
	}
	if code := r.FormValue("code"); code != "12345" {
		c.Errorf("Wrong code: %v", code)
		http.Error(w, "{\"status\":\"Code invalid! Try again\", \"code\":401}", http.StatusUnauthorized)
	} else if err := mail.Send(c, msg); err != nil {
		c.Errorf("Couldn't send email: %v", err)
		http.Error(w, "{\"status\":\"Mail NOT send! Error\", \"code\":500}", http.StatusInternalServerError)
	} else {
		c.Infof("Mail send:\n %v", message)
		fmt.Fprint(w, "{\"status\":\"Mail send\", \"code\":200}")
	}
}
Ejemplo n.º 11
0
func contact(w http.ResponseWriter, r *http.Request) {
	var submitted string
	if r.Method == "POST" {
		c := appengine.NewContext(r)
		name := r.FormValue("name")
		email := r.FormValue("email")
		info := r.FormValue("info")
		if name == "" || email == "" || info == "" {
			submitted = "Submission failed. Please enter all the information on the form. Thanks!"
		} else {
			msg := &mail.Message{
				Sender:   "*****@*****.**",
				To:       []string{"*****@*****.**"},
				Subject:  fmt.Sprintf("Website Contact - %s", name),
				Body:     fmt.Sprintf("Name: %s\nEmail: %s\nInformation: %s", name, email, info),
				HTMLBody: fmt.Sprintf("<html><body><p>Name: %s</p><p>Email: %s</p><p>Information: %s</p></body></html>", name, email, info),
			}
			if err := mail.Send(c, msg); err != nil {
				c.Errorf("Could not send email: %v", err)
				submitted = "Your information could not be sent. Could you try again later? Apologies!"
			} else {
				submitted = "Your information has been sent. I'll get back to you as soon as possible!"
			}
		}
		c.Infof("Contact submitted: name=%s, email=%s, info=%s", name, email, info)
	}
	out := mustache.RenderFileInLayout("mustache/contact.html.mustache", "mustache/layout.html.mustache", map[string]string{"submitted": submitted})
	fmt.Fprint(w, out)
}
Ejemplo n.º 12
0
func emailSend(w http.ResponseWriter, r *http.Request, m map[string]string) {

	c := appengine.NewContext(r)
	//addr := r.FormValue("email")

	if _, ok := m["subject"]; !ok {
		m["subject"] = "empty subject line"
	}

	email_thread_id := []string{"3223"}

	msg := &ae_mail.Message{
		//Sender:  "Peter Buchmann <*****@*****.**",
		//		Sender: "*****@*****.**",
		Sender: "*****@*****.**",
		//To:	   []string{addr},
		To: []string{"*****@*****.**"},

		Subject: m["subject"],
		Body:    "some_body some_body2",
		Headers: go_mail.Header{"References": email_thread_id},
	}
	err := ae_mail.Send(c, msg)
	util_err.Err_http(w, r, err, false, "could not send the email")

}
Ejemplo n.º 13
0
// MailNotifications finds all the users interested in the topic of the conference
// and sends them an email notifying the conference.
//
// This operation can be slow and shouldn't be performed in the critical path of the
// application.
func (conf *Conference) MailNotifications(ctx appengine.Context, sender, subject, body string) error {
	ks, err := datastore.NewQuery(UserKind).
		Filter("Topics =", conf.Topic).
		KeysOnly().
		GetAll(ctx, nil)
	if err != nil {
		return fmt.Errorf("get interested users: %v", err)
	}

	to := make([]string, len(ks))
	for i, k := range ks {
		to[i] = k.StringID()
	}

	msg := &mail.Message{
		Sender:  sender,
		To:      to,
		Subject: subject,
		Body:    body,
	}
	if err := mail.Send(ctx, msg); err != nil {
		return fmt.Errorf("send mail: %v", err)
	}
	return nil
}
Ejemplo n.º 14
0
Archivo: web.go Proyecto: mufniarz/OLMC
func contactRequestHandler(w http.ResponseWriter, r *http.Request) {
	name := r.FormValue("name")
	email := r.FormValue("email")
	subject := r.FormValue("subject")
	message := r.FormValue("message")

	if len(email) == 0 {
		fmt.Fprint(w, "invalid request")
		return
	}

	context := appengine.NewContext(r)

	mailMessage := &mail.Message{
		Sender:  name + " <*****@*****.**>",
		ReplyTo: email,
		To:      []string{"*****@*****.**"},
		Subject: subject,
		Body:    message,
	}

	if error := mail.Send(context, mailMessage); error != nil {
		context.Errorf("the email could not be sent: %v", error)
	}

	http.ServeFile(w, r, "static/html/contact/contact_sent.html")
}
Ejemplo n.º 15
0
// Sends post notification mail
func SendMail(c appengine.Context, entry Entry) error {
	config, err := ParseConfig("./config/mailConfig.json")
	if err != nil {
		return err
	}

	// Prepares email message
	msg := new(mail.Message)
	msg.Sender = config.Sender
	msg.To = make([]string, 1)
	msg.To[0] = config.To
	msg.Subject = "New post made from Legacy-BBS-Go"
	var body bytes.Buffer
	var mailTemplate = template.Must(template.ParseFiles("template/notificationMailTemplate.txt"))
	if err := mailTemplate.Execute(&body, entry); err != nil {
		return err
	}
	msg.Body = body.String()
	if err := mail.Send(c, msg); err != nil {
		return err
	}

	c.Infof("Notification mail sent to \"" + config.To + "\"")

	return nil
}
Ejemplo n.º 16
0
func doInitiateVerifyEmail(c *Context) error {
	// Create the VerifyEmail record.
	v := &VerifyEmail{
		UserId:    c.Session().UserId,
		Timestamp: time.Now(),
	}
	key := NewEphemeralKey(c.Aec(), "VerifyEmail")
	key, err := datastore.Put(c.Aec(), key, v)
	if err != nil {
		return err
	}

	// Send the email.
	verifUrl := prependHost(fmt.Sprintf("/account/verif?key=%s", key.Encode()), c)
	data := map[string]interface{}{
		"fullName": c.Session().FullName,
		"verifUrl": verifUrl,
	}
	body, err := ExecuteTextTemplate("email-verif.txt", data)
	if err != nil {
		return err
	}

	msg := &mail.Message{
		Sender:  "Tadue <*****@*****.**>",
		To:      []string{c.Session().Email},
		Subject: "Welcome to Tadue",
		Body:    body,
	}
	return mail.Send(c.Aec(), msg)
}
Ejemplo n.º 17
0
func sendSubscription(addr string, c appengine.Context) {
	code := getSubCode()
	msg := &gaeMail.Message{
		Sender:  "*****@*****.**",
		To:      []string{addr},
		Subject: "confirm " + code,
		Body:    "Reply without changing subject",
	}
	if err := gaeMail.Send(c, msg); err != nil {
		c.Errorf("Couldn't send email to %s for %s: %v", addr, code, err)
	}

	// XXXX if successful, register the code as (email, code, 0 (retry)) tuple.
	confirmation := Confirmation{
		Email: addr,
		Code:  code,
		Retry: 0,
	}

	_, err := datastore.Put(c,
		datastore.NewIncompleteKey(c, CONFIRM_MODEL, nil),
		&confirmation)
	if err != nil {
		c.Errorf("Couldn't write confirmation code for %s, %s: %v", addr, code, err)
		return
	}
	c.Infof("Wrote confirmation successfully for %s, %s", addr, code)
}
Ejemplo n.º 18
0
func handleInviteByMail(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	_, _, err := getSession(c, r)
	if err != nil {
		sendError(w, r, "No session cookie")
		return
	}

	blob, err := ioutil.ReadAll(r.Body)
	if err != nil {
		sendError(w, r, "Error reading request body")
		return
	}
	r.Body.Close()

	var req inviteByMail
	err = json.Unmarshal(blob, &req)
	if err != nil {
		sendError(w, r, "Malformed request body: "+err.String())
		return
	}

	msg := &mail.Message{
		Sender:  "*****@*****.**",
		To:      []string{req.UserName},
		Subject: "Invitation to LightWave",
		Body:    req.Content,
	}
	if err := mail.Send(c, msg); err != nil {
		sendError(w, r, "Could not send mail")
		c.Errorf("Couldn't send email: %v", err)
	}
}
Ejemplo n.º 19
0
func handler(w http.ResponseWriter, r *http.Request) {
	context := appengine.NewContext(r)
	sendEmail := true

	// Load config data from datastore
	key := datastore.NewKey(context, "Environment", "env", 0, nil)
	var env Environment
	if err := datastore.Get(context, key, &env); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Construct the email message to send.
	sortedKeys := make([]string, len(r.Header))
	i := 0
	for k, _ := range r.Header {
		sortedKeys[i] = k
		i++
	}
	sort.Strings(sortedKeys)

	var buffer bytes.Buffer
	for _, k := range sortedKeys {
		v := r.Header[k]
		buffer.WriteString(fmt.Sprintf("%s: %s\n", k, v))
	}
	buffer.WriteString(fmt.Sprintf("Remote-Addr: %s\n", r.RemoteAddr))

	path := r.URL.Path[1:]
	buffer.WriteString(path)

	if sendEmail {
		msg := &mail.Message{
			Sender:  env.SendFrom,
			To:      []string{env.SendTo},
			Subject: "See-through Signal",
			Body:    buffer.String(),
		}

		if err := mail.Send(context, msg); err != nil {
			context.Errorf("Couldn't send email: %v", err)
		}
	}

	w.Header().Set("Content-Type", "image/gif")
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")

	gif, err := ioutil.ReadFile("pixel.gif")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprint(w, string(gif))
}
Ejemplo n.º 20
0
Archivo: mail.go Proyecto: scotch/aego
func Send(c context.Context, m *TemplateMessage) (err error) {
	if err = m.Execute(); err != nil {
		return
	}
	if err = mail.Send(c, m.Message); err != nil {
		c.Errorf("email: sending confirmation email to %v failed: %v", m.To, err)
		return
	}
	return nil
}
Ejemplo n.º 21
0
/**
 * メールの送信
 * @function
 * @param {appengine.Context} c コンテキスト
 * @param {string} sender 送信元アドレス
 * @param {string} to 送信先アドレス
 * @param {string} subject タイトル
 * @param {string} body メッセージ
 */
func sendMail(c appengine.Context, sender string, to string, subject string, body string) {
	message := new(mail.Message)
	message.Sender = sender
	message.To = []string{to}
	message.Subject = subject
	message.Body = body

	err := mail.Send(c, message)
	check(c, err)
}
Ejemplo n.º 22
0
func SendMail(c appengine.Context, from, to, body string) error {
	msg := &appmail.Message{
		Sender:  from,
		ReplyTo: from,
		To:      []string{to},
		Body:    body,
	}

	return appmail.Send(c, msg)
}
Ejemplo n.º 23
0
func updateGameDispute(w http.ResponseWriter, r *http.Request, seasonId string, weekNumber int, gameIndex int) {
	c := appengine.NewContext(r)
	winnerName := r.FormValue("winnerName")
	player1Name := r.FormValue("player1Name")
	player2Name := r.FormValue("player2Name")
	isDisputed, err := strconv.ParseBool(r.FormValue("isDisputed"))
	if err != nil {
		panic(err)
	}

	season := LoadSeasonById(c, seasonId)

	const emailMessage = `
	A dispute was submitted for the game between
	%s and %s.
	
	Winner: %s
	`

	const emailSubject = `
	"%s -- Automated Dispute Notification"
	`

	var emailList []string
	emailList = []string{"dungeongod" + "@" + "gmail" + ".com"}

	msg := &mail.Message{
		Sender:  "",
		To:      emailList,
		Subject: fmt.Sprintf(emailSubject, season.Name),
		Body:    fmt.Sprintf(emailMessage, player1Name, player2Name, winnerName),
	}
	if err := mail.Send(c, msg); err != nil {
		c.Errorf("Couldn't send email: %v", err)
	}

	var weeks []model.Week
	err2 := json.Unmarshal(season.Schedule, &weeks)
	if err2 != nil {
		panic(err2)
	}
	game := &(weeks[weekNumber-1].Games[gameIndex])
	game.IsDisputed = isDisputed
	c.Infof("Disputing game %v, %v: %v", weekNumber, gameIndex, weeks)
	newSchedule, err := json.Marshal(weeks)
	if err != nil {
		panic(err)
	}
	season.Schedule = newSchedule
	err = model.SaveSeason(c, *season)
	if err != nil {
		panic(err)
	}
}
Ejemplo n.º 24
0
func sendReceipt(c appengine.Context, dst, body string) {
	msg := &mail.Message{
		Sender:  appAdmin,
		To:      []string{dst},
		Subject: "Your Gopher Mart receipt",
		Body:    body,
	}
	if err := mail.Send(c, msg); err != nil {
		c.Errorf("mail.Send: %v", err)
	}
}
Ejemplo n.º 25
0
func CLWAReportErrorThroughMail(r *http.Request, subject string, finalHTML string) error {
	c := appengine.NewContext(r)
	msg := &mail.Message{
		Sender:   ATD,
		To:       []string{ATD},
		Subject:  subject + " [CLWACRM-ERR][CLWACRM]",
		HTMLBody: finalHTML,
	}

	return mail.Send(c, msg)
}
Ejemplo n.º 26
0
func sendEmail(price float64, c appengine.Context) {
	msg := &mail.Message{
		Sender:  SENDER,
		To:      []string{"<RECIPIENT_EMAIL_ADDRESSES"}, //comma-delimited email addresses
		Subject: "Steam Item price dropped below threshold",
		Body:    fmt.Sprintf(MESSAGE, ITEM_URL, THRESHOLD, price),
	}

	if err := mail.Send(c, msg); err != nil {
		c.Errorf("Couldn't send email: %v", err)
	}
}
Ejemplo n.º 27
0
func SendEmailToAdmin(c appengine.Context, subject, htmlbody string) {
	msg := &mail.Message{

		Sender:   kSenderEmail, // cap.Profile.EmailAddress,
		To:       []string{kAdminEmail},
		Subject:  subject,
		HTMLBody: htmlbody,
	}

	if err := mail.Send(c, msg); err != nil {
		c.Errorf("Could not send adminemail to <%s>: %v", kAdminEmail, err)
	}
}
Ejemplo n.º 28
0
func handleCronInstances(w http.ResponseWriter, r *http.Request) {
	states := getInstanceStates(r)
	msg := &mail.Message{
		Sender:  "Ninetan <*****@*****.**>",
		To:      []string{"*****@*****.**"},
		Subject: fmt.Sprintf("%d EC2 instances are running", states["running"]),
		Body:    fmt.Sprintf("%v", states)}
	if err := mail.Send(appengine.NewContext(r), msg); err != nil {
		panic(err)
	}
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintln(w, "OK")
}
Ejemplo n.º 29
0
func sendmail(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	//calculate the moon phase start
	t := time.Now()
	var g, e int

	month := t.Month()
	year := t.Year()
	day := t.Day()

	if month == 1 {
		day--
	} else if month == 2 {
		day += 30
	} else {
		day += 28 + (int(month)-2)*3059/100
		// adjust for leap years
		ch := year & 3
		if ch != 0 {
			day++
		}
		if (year % 100) == 0 {
			day--
		}
	}
	g = (year-1900)%19 + 1
	e = (11*g + 18) % 30
	if (e == 25 && g > 11) || e == 24 {
		e++
	}
	b := (((e+day)*6 + 11) % 177) / 22 & 7
	//end moon phase calculation
	if b == 3 {
		q := datastore.NewQuery("Contact").Order("DateAdded")
		var contacts []Contact
		_, err := q.GetAll(c, &contacts)
		for _, p := range contacts {
			msg := &mail.Message{
				Sender:  "Go Islamic Support <*****@*****.**>",
				To:      []string{p.Email},
				Subject: "You have new notifications waiting for you",
				Body:    fmt.Sprintf(notificationMessage, p.Email),
			}
			if err = mail.Send(c, msg); err != nil {
				c.Errorf("Cannot send email: %v", err)
			}
		}
	}
}
Ejemplo n.º 30
0
func emailHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if r.Method != "POST" {
		c.Errorf("messageHandler did not expect %s", r.Method)
		http.Error(w, "Method not allowed.", http.StatusInternalServerError)
		return
	}

	vm := JsonVM{false, nil, nil}

	candidateNote := `
Hi,

Congratulations on securing a code interview!  The link below is 
your invitation to a Koderank session, where you will have the 
opportunity to demonstrate your problem solving abilities live. 

http://koderank.appspot.com/whiteboard?x=%s

In-browser voice chat will be availble during the interview 
(Adobe Flash required).  Visit the link below to adjust and test 
your microphone/speakers before connecting.

http://clientsupport.twilio.com

Good luck!

The Koderank team
`
	code := r.FormValue("code")
	email := r.FormValue("email")

	msg := &mail.Message{
		Sender:  "Koderank <*****@*****.**>",
		To:      []string{email},
		Subject: "Koderank online code interview",
		Body:    fmt.Sprintf(candidateNote, code),
	}

	if err := mail.Send(c, msg); err != nil {
		c.Errorf("mail.Send: %s", err)
		vm.Messages = []string{"There was a problem sending the email."}
		renderJson(w, c, vm)
		return
	}

	vm.IsSuccess = true
	vm.Messages = []string{"Email sent."}
	renderJson(w, c, vm)
}